How can I make a dictionary that marks itself when it's modified?

Kent Johnson kent at kentsjohnson.com
Fri Jan 13 08:09:02 EST 2006


sandravandale at yahoo.com wrote:
> Thanks to everyone who posted comments or put some thought into this
> problem.
> 
> I should have been more specific with what I want to do, from your
> comments the general case of this problem, while I hate to say
> impossible, is way more trouble than it's worth.
> 
> By modified I meant that the dictionary has been changed from its
> original (constructed) state by either:
> 1) A new element was added
> 2) An existing element was changed
> 
> I want to wrap a dictionary of cookies in mod_python. Cookies are
> represented as objects with no methods. In light of this and Michael's
> excellent post, I came up with the following code.
> 
> class CookieCollection(dict):
>    def __init__(self, d):
>       for k, v in d:
>          v.__setattr__ = self.__wrap_setattr(v.__setattr__)
>          self[k] = v

I don't think this will work if v is an instance of a new-style class - 
for new-style classes, special methods are always looked up on the 
class, you can't override them in an instance. For example:

  >>> class foo(object):
  ...   def __setattr__(self, attr, value):
  ...     print 'foo.__setattr__'
  ...     object.__setattr__(self, attr, value)
  ...
  >>> f=foo()
  >>> f.x = 3
foo.__setattr__
  >>> def new_setattr(attr, value):
  ...   print 'new_setattr'
  ...
  >>> f.__setattr__ = new_setattr
foo.__setattr__
  >>> f.y=3
foo.__setattr__

still calls foo.__setattr__()

Kent



More information about the Python-list mailing list