【发布时间】:2022-11-10 02:31:19
【问题描述】:
看看下面的代码sn -p
Python 3.10.1 (main, Dec 10 2021, 10:36:36) [Clang 12.0.5 (clang-1205.0.22.11)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from shelve import DbfilenameShelf as db
>>> x = db("test") ## create a new Shelf object of type DbfilenameShelf
>>> x["k1"] = "v1" ## add some data to shelf object
>>> x
<shelve.DbfilenameShelf object at 0x105416260>
>>> dict(x) ## let's check what's in the shelf
{'k1': 'v1'}
>>> x.writeback ## writeback is set to False (the default value)
False
>>> x.close() ## cool .. let's close the shelf with writeback=False
>>> dict(x) ## this should not work anymore since shelf is closed
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/_collections_abc.py", line 878, in __iter__
yield from self._mapping
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/shelve.py", line 95, in __iter__
for k in self.dict.keys():
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/shelve.py", line 70, in closed
raise ValueError('invalid operation on closed shelf')
ValueError: invalid operation on closed shelf
>>> y = db("test") ## opening test.db again
>>> dict(y) ## how did shelf writeback to disk ?
{'k1': 'v1'}
>>> y.writeback ## writeback is still false
False
在代码 sn-p 中,我创建了一个新的 DbfilenameShelf,并在 Shelf 对象中设置了 writeback=False。
当我关闭架子对象并重新打开它时,我看到数据已保留。
我认为需要将数据保存到磁盘writeback=True。但情况似乎并非如此。
如果 Shelf 缓存中的数据被刷新并写入磁盘,writeback 有什么意义?
【问题讨论】:
标签: python python-3.x shelve