How to detect modification of a nested object in Python?

Let's 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__

only called when the object itself changes:

 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 such a case, or is there another way I should be doing this? My goal is to have a dictionary-like object that is always in sync with the file on disk.

+3


source to share


1 answer


I would suggest using shelve

. I provide a permanent dictionary. Opening a file with writeback=True

force syncs with the file:

db = shelve.open('test.db', writeback=True)

      

Treat it the same as a dict:

>>> db['a'] = {}
>>> db['a']['x'] = 10
>>> dict(db)
{'a': {'x': 10}}

      



Close reopening:

>>> db.close()
>>> db = shelve.open('test.db', writeback=True)
>>> dict(db)
{'a': {'x': 10}}

      

The data still exists.

+1


source







All Articles