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

sandravandale at sandravandale at
Thu Jan 12 19:58:02 EST 2006

Thanks to everyone who posted comments or put some thought into this

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

      self.modified = False

   def __setitem__(self, key, value):
      super(dict, self).__setitem__(key, value)
      self.modified = True # we don't have to wrap this item, the dict
is modified, and can't ever be unmodified

   def __wrap_setattr(self, real_setattr):
      def setattr(attrname, val):
         self.modified = True
         real_setattr(attrname, val)
      return setattr

   def send(self, req):
      if self.modified:
         for cookie in req.cookies.values():
            Cookie.add_cookie(req, cookie)

The purpose of which is to be able to store any cookies sent with the
request in the CookieCollection, and then automatically call send()
before the headers are finished being sent and it will only do
something if the cookies have been altered (otheriwse they don't need
to be sent again.) I haven't tested the code yet, but the general idea
should be correct at the very least I think.

Thanks again,

More information about the Python-list mailing list