python - Setting an Item in nested dictionary with __setitem__ -


here's did, trying create wrapper dict-like database, among other functions:

    class database(object):         def __init__(self, name):             self.name = name             self.db = anydbm.open(name, 'c')          def __getitem__(self, key):             key = str(key)             try:                 self.db = anydbm.open(self.name, 'w')              except exception,e:                  raise e             else:                 return cpickle.loads(self.db[key])             finally:                   self.db.close()          def __setitem__(self, key, value):             key = str(key)             value = cpickle.dumps(value)             try:                 self.db = anydbm.open(self.name, 'w')             except exception,e:                 print e              else:                 self.db[key] = value             finally:                   self.db.close() 

when try define new key in dict nested within, seems getitem returning value instead of reference, definition not modified after setitem.

>>> database import database >>> db = database('test') >>> db['a'] = {'alpha':'aaa'} >>> db['a']['alpha'] = 'bbb' >>> print db {'a': {'alpha': 'aaa'}} //the value not modified 

well, have understand doing:

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

is equivalent to

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

so dumps dict disk. when do

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

you first load dict disk

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

and change dict:

tmp['alpha'] = 'bbb' 

this has no effect on data dumped disk, because object not involved anymore.

to make work cannot return simple dict, instead need object tracks changes , writes them disk.

btw, you're writing shelve. has same problem:

because of python semantics, shelf cannot know when mutable persistent-dictionary entry modified. default modified objects written when assigned shelf (see example). if optional writeback parameter set true, entries accessed cached in memory, , written on sync() , close(); can make handier mutate mutable entries in persistent dictionary, but, if many entries accessed, can consume vast amounts of memory cache, , can make close operation slow since accessed entries written (there no way determine accessed entries mutable, nor ones mutated).


Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -