Detecting changes to a dict

Scott David Daniels Scott.Daniels at Acm.Org
Mon Sep 28 10:29:50 EDT 2009


Steven D'Aprano wrote:
> I'm pretty sure the answer to this is No, but I thought I'd ask just in 
> case... 
> Is there a fast way to see that a dict has been modified? ...
> 
> Of course I can subclass dict to do this, but if there's an existing way, 
> that would be better.

def mutating(method):
     def replacement(self, *args, **kwargs):
         try:
             return method(self, *args, **kwargs)
         finally:
             self.serial += 1
     replacement.__name__ = method.__name__
     return replacement


class SerializedDictionary(dict):
     def __init__(self, *arg, **kwargs):
         self.serial = 0
         super(SerializedDictionary).__init__(self, *arg, **kwargs)

     __setitem__ = mutating(dict.__setitem__)
     __delitem__ = mutating(dict.__delitem__)
     clear = mutating(dict.clear)
     pop = mutating(dict.pop)
     popitem = mutating(dict.popitem)
     setdefault = mutating(dict.setdefault)
     update = mutating(dict.update)

d = SerializedDictionary(whatever)

Then just use dict.serial to see if there has been a change.

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list