pythonlistdictionaryhook

Implement hooks for list & dict changes


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 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.

How do I hook mutators of given structures? Is there something I don't know?


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