trapping dict alterations in a class

Michael Hudson mwh21 at cam.ac.uk
Sun Apr 16 18:24:42 EDT 2000


Michael Esveldt <dante at oz.net> 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.

Eg:

import UserDict

class Wrapper(UserDict.UserDict):
    def __setitem__(self,item,value):
        print item, value
        UserDict.UserDict.__setitem__(self,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.

HTH,
Michael

-- 
81. In computing, turning the obvious into the useful is a living
    definition of the word "frustration".
     -- Alan Perlis, http://www.cs.yale.edu/~perlis-alan/quotes.html



More information about the Python-list mailing list