想要update/modify key 的值搁置
Want to update/modify the value of key in shelve
我有一个数据(即{'/domflight': 10, '/intlflight': 20}
),想将'/domflight'
的值修改为50
。以下是我正在尝试执行但没有成功的代码。
import shelve
s = shelve.open('/tmp/test_shelf.db')
try:
print s['key1']
s['key1']['/domflight'] = 50
finally:
s.close()
s = shelve.open('/tmp/test_shelf.db', writeback=True)
try:
print s['key1']
finally:
s.close()
搁置无法检测对嵌套可变对象的更改。在嵌套字典中设置键不会触发保存。
改为重新设置字典:
nested_dict = s['key1']
nested_dict['/domflight'] = 50
s['key1'] = nested_dict
返回 s['key1']
的任务触发了保存。
从技术上讲,s
是 UserDict.DictMixin
class 的子 class,具有自定义 __setitem__
方法。直接分配给 s
对象中的键会调用该方法并保存更改。但是分配给一个 嵌套 的可变对象不会触发对 __setitem__
的调用,因此不会检测到更改,也不会保存任何内容。
这是covered in the documentation:
Because of Python semantics, a shelf cannot know when a mutable persistent-dictionary entry is modified. By default modified objects are written only when assigned to the shelf (see Example). If the optional writeback parameter is set to True
, all entries accessed are also cached in memory, and written back on sync()
and close()
; this can make it handier to mutate mutable entries in the persistent dictionary, but, if many entries are accessed, it can consume vast amounts of memory for the cache, and it can make the close operation very slow since all accessed entries are written back (there is no way to determine which accessed entries are mutable, nor which ones were actually mutated).
我有一个数据(即{'/domflight': 10, '/intlflight': 20}
),想将'/domflight'
的值修改为50
。以下是我正在尝试执行但没有成功的代码。
import shelve
s = shelve.open('/tmp/test_shelf.db')
try:
print s['key1']
s['key1']['/domflight'] = 50
finally:
s.close()
s = shelve.open('/tmp/test_shelf.db', writeback=True)
try:
print s['key1']
finally:
s.close()
搁置无法检测对嵌套可变对象的更改。在嵌套字典中设置键不会触发保存。
改为重新设置字典:
nested_dict = s['key1']
nested_dict['/domflight'] = 50
s['key1'] = nested_dict
返回 s['key1']
的任务触发了保存。
从技术上讲,s
是 UserDict.DictMixin
class 的子 class,具有自定义 __setitem__
方法。直接分配给 s
对象中的键会调用该方法并保存更改。但是分配给一个 嵌套 的可变对象不会触发对 __setitem__
的调用,因此不会检测到更改,也不会保存任何内容。
这是covered in the documentation:
Because of Python semantics, a shelf cannot know when a mutable persistent-dictionary entry is modified. By default modified objects are written only when assigned to the shelf (see Example). If the optional writeback parameter is set to
True
, all entries accessed are also cached in memory, and written back onsync()
andclose()
; this can make it handier to mutate mutable entries in the persistent dictionary, but, if many entries are accessed, it can consume vast amounts of memory for the cache, and it can make the close operation very slow since all accessed entries are written back (there is no way to determine which accessed entries are mutable, nor which ones were actually mutated).