overriding __getitem__ for a subclass of dict

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Tue Nov 17 02:46:05 CET 2009

On Mon, 16 Nov 2009 10:32:19 -0800, Steve Howell wrote:

> Actually, the __getitem__ workaround that I proposed earlier only works
> on subclasses of dict, not dict themselves.  So given a pure dictionary
> object, it is impossible to hook into attribute lookups after
> instantiation in debugging/tracing code.

If you have written your application to avoid unnecessary isinstance and 
type checks, i.e. to use duck-typing, then a technique you might find 
useful is delegation.

class DebuggingDict(object):
    def __init__(self, dict_to_wrap, hook=None):
        self.__dict__['_d'] = dict_to_wrap
        self.__dict__['getitem_hook'] = hook
    def __getattr__(self, name):
        return getattr(self._d, name)
    def __setattr__(self, name, value):
        setattr(self._d, name, value)
    def __getitem__(self, key):
        if self.getitem_hook is not None:
            self.getitem_hook(self, key)
        return self._d[key]

And in use:

>>> def hook(self, key):
...     print "Looking for key", key
>>> d = DebuggingDict({1:'a', 2: 'b'}, hook)
>>> d[1]
Looking for key 1
>>> d[2]
Looking for key 2


More information about the Python-list mailing list