Python 3: hook list & dict changes

hook, python, python-3.x

Solution

Subclassing dict maybe:

class DictWatch(dict):
    def __init__(self, *args, **kwargs):
        self.callback = kwargs.pop('callback')
        dict.__init__(self, args)

    def __setitem__(self, key, val):
        # YOUR HOOK HERE
        self.callback(key, val)
        dict.__setitem__(self, key, val)

    # and other overrided dict methods if you need them

Demo:

>>> def cb(k,v):
...     print k,v
... 
>>> d=DictWatch(callback=cb)
>>> d['key']='100'
key 100

Problem

My app relies on `list` and `dict` data structures for maintaining current state. Now I need to track whenever element is added/removed from list or dict data changes. I've googled and found out that there are `collections.abc.Sequence` (for list) and `collections.abc.MutableMapping` (for dict), but they're very limited and result can't be used instead of list/dict (`append`, `clear`, ...). I've been thinking about some proxy class that'll forward calls and provide hooks to be called before/after some method is forwarded, but didn't find anything that even looks like in. So my question is: how do I hook mutators of given structures? Is there something I don't know?

Original source