试图在Sh中存储deque的奇怪行为

2024-10-01 11:26:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我将让下面的终端会话自己发言:

>>> import shelve
>>> s = shelve.open('TestShelve')
>>> from collections import deque
>>> s['store'] = deque()
>>> d = s['store']
>>> print s['store']
deque([])
>>> print d
deque([])
>>> s['store'].appendleft('Teststr')
>>> d.appendleft('Teststr')
>>> print s['store']
deque([])
>>> print d
deque(['Teststr'])

d和{}不应该指向同一个对象吗?为什么appendleftd起作用,而对{}不起作用?在


Tags: 对象storefromimport终端opencollectionsshelve
2条回答

结果发现它们不一样,因此对它们执行的任何操作都不匹配:

>>> import shelve
>>> s = shelve.open('TestShelve')
>>> from collections import deque
>>> s['store'] = deque()
>>> d = s['store']
>>> id(s['store'])
27439296
>>> id(d)
27439184

要在编码时修改项目,需要传递参数writeback=True

^{pr2}$

请参阅文档:

If the writeback parameter is True, the object will hold a cache of all entries accessed and write them back to the dict at sync and close times. This allows natural operations on mutable entries, but can consume much more memory and make sync and close take a long time.

您也可以使用writeback=False来执行此操作,但是您需要按照提供的示例编写代码:

# having opened d without writeback=True, you need to code carefully:
temp = d['xx']      # extracts the copy
temp.append(5)      # mutates the copy
d['xx'] = temp      # stores the copy right back, to persist it

shelve正在pickle对对象进行序列化。当然,这是复制品。因此,从shelve返回的对象将与您放入的对象具有不同的标识,尽管它们将是等效的。在

如果这很重要,您可以编写一个deque子类,每当它被修改时,它会自动重新上架,尽管在许多用例中这可能会有很差的性能。在

相关问题 更多 >