Setting an Item in nested dictionary with __setitem__

最后都变了- 提交于 2019-12-05 16:25:18

Well, you have to understand what you are doing:

db['a'] = {'alpha':'aaa'}

is equivalent to

db.__setitem__('a', {'alpha':'aaa'})

so this dumps the dict to the disk. However when you do

db['a']['alpha'] = 'bbb'

you first load the dict from disk

tmp = db.__getitem__('a') # except tmp is pushed on the stack

and then change this dict:

tmp['alpha'] = 'bbb'

This obviously has no effect on the data dumped to disk, because your object is not involved anymore.

To make this work you cannot return a simple dict, but instead you need another object that tracks changes and writes them back to disk.

Btw, you're writing shelve. It has the same problem:

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).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!