Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect dict modification?

I have subclassed the dict and need to detect all its modifications.

(I know I cannot detect an in-place modification of a stored value. That's OK.)

My code:

def __setitem__(self, key, value):
    super().__setitem__(key, value)
    self.modified = True

def __delitem__(self, key):
    super().__delitem__(key)
    self.modified = True

The problem is it works only for a straightforward assignment or deletion. It does not detect changes made by pop(), popitem(), clear() and update().

Why are __setitem__ and __delitem__ bypassed when items are added or deleted? Do I have to redefine all those methods (pop, etc.) as well?

like image 393
VPfB Avatar asked Dec 20 '15 11:12

VPfB


2 Answers

For this usage, you should not subclass dict class, but instead use the abstract classes form the collections module of Python standard library.

You should subclass the MutableMapping abstract class and override the following methods: __getitem__, __setitem__, __delitem__, __iter__ and __len__, all that by using an inner dict. The abstract base class ensures that all other methods will use those ones.

class MyDict(collections.MutableMapping):
    def __init__(self):
        self.d = {}
        # other initializations ...

    def __setitem__(self, key, value):
        self.d[key] = value
        self.modified = true
    ...
like image 200
Serge Ballesta Avatar answered Oct 06 '22 12:10

Serge Ballesta


pop, popitem, clear, update are not implemented through __setitem__ and __delitem__.

You must redefine them also.

I can suggest look at OrderedDict implementation.

like image 36
Alex Yu Avatar answered Oct 06 '22 11:10

Alex Yu