【问题标题】:Shelve module: What's the point of 'writeback' variable?搁置模块:“写回”变量有什么意义?
【发布时间】: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


    【解决方案1】:

    您似乎误解了writeback 的含义。

    Writeback 是一种缓存方法,其中最新数据最初仅写入缓存,仅在定期或满足某些条件时才写回辅助存储。它与write-through 方法相反,后者在将数据写入缓存后立即将数据同步写入辅助存储。 你可以看看this answer。

    您还可以阅读python docs for Shelve 关于写回参数。

    如果可选的 writeback 参数设置为 True,则所有访问的条目也会缓存在内存中,并在 sync() 和 close() 上写回;这可以更方便地改变持久字典中的可变条目,但是,如果访问了许多条目,它会消耗大量内存用于缓存,并且由于所有访问的条目都被写回,因此关闭操作会非常慢

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-30
      • 2018-01-07
      • 2011-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多