Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect modification of nested object in Python?

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.

like image 788
Jimmy Avatar asked Jan 31 '26 09:01

Jimmy


1 Answers

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.

like image 195
Mike Müller Avatar answered Feb 01 '26 22:02

Mike Müller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!