Say I have something like this (not tested):
class Foo(object):
def __init__(self):
self.store = {}
def __setitem__(self, key, value):
self.store[key] = value
print('Detected set')
def __getitem__(self, key):
return self.store[key]
__setitem__ is only called when the object itself is changed:
foo = Foo()
foo['bar'] = 'baz'
But it is not called, for example, when:
foo['bar'] = {}
foo['bar']['baz'] = 'not detected inside dict'
How can I detect this kind of case, or is there some other way I should be doing this? My goal is to have a dictionary-like object that is always in-sync with a file on disk.
I would suggest using shelve. I provides a persistent dictionary.
Opening a file with writeback=True forces synchronization with the file:
db = shelve.open('test.db', writeback=True)
Treat it just like a dict:
>>> db['a'] = {}
>>> db['a']['x'] = 10
>>> dict(db)
{'a': {'x': 10}}
Close an re-open:
>>> db.close()
>>> db = shelve.open('test.db', writeback=True)
>>> dict(db)
{'a': {'x': 10}}
The data is still there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With