trapping dict alterations in a class

Michael Hudson mwh21 at
Mon Apr 17 00:24:42 CEST 2000

Michael Esveldt <dante at> writes:

> I want to be able to do for a dictionary in a given class what 
> __setattr__ does for variable binding.
> class foo:
>     def __setattr__(self, name, value):
>         print name, value
>         self.__dict__[name] = value
> bar = foo()
> bar.quux = 1
> bar.baz = {"key":"value"}
> The above obviously prints "quux 1" and then "baz {'key':'value'}". But 
> what if I want to trap further alterations to the foo.baz dictionary? Is 
> this possible?

Well, you could implement __getattr__ and then when asked for "baz"
return a wrapper to the dictionary.


import UserDict

class Wrapper(UserDict.UserDict):
    def __setitem__(self,item,value):
        print item, value

class Foo:
    def __init__(self):
        self.__dict__['magic'] = {}
    def __setattr__(self,attr,value):
        print attr, value
        self.magic[attr] = value
    def __getattr__(self,attr):
        return Wrapper(self.magic[attr])

This is far from being complete (writing __{get,set}attr__ methods is
a tricky and subtle business), but it's a start.  Watch out for
cycles, too.


81. In computing, turning the obvious into the useful is a living
    definition of the word "frustration".
     -- Alan Perlis,

More information about the Python-list mailing list