how to detect if a dictionary has been modified ?

Glenn Linderman v+python at g.nevcal.com
Sun Nov 23 12:19:38 EST 2008


On approximately 11/23/2008 1:40 AM, came the following characters from 
the keyboard of Steven D'Aprano:
> On Sun, 23 Nov 2008 01:18:17 -0800, bearophileHUGS wrote
>> Stef Mientki:
>>     
>>> I would like to detect if a dictionary has been changed. So I would
>>> like to have a modified-flag.
>>>       
>> A solution is of course to create a SDict class, that works like a
>> normal dict, and also watches for changes and has an extra boolean
>> attribute.
>>     
>
> What does the S stand for?
>
> Untested and possibly incomplete:
>
> def factory(methodname, cls=dict, flag=True):
>     def method(self, *args, **kwargs):
>         self.modified = flag
>         return getattr(cls, methodname)(self, *args, **kwargs)
>     return method
>
>
> class SDict(dict):
>     __init__ = factory('__init__', flag=False)
>     __setitem__ = factory('__setitem__')
>     __delitem__ = factory('__delitem__')
>     clear = factory('clear')
>     pop = factory('pop')
>     popitem = factory('popitem')
>     setdefault = factory('setdefault')
>     update = factory('update')
>   

Interesting technique.  I must point out, though, that it doesn't 
indicate if a dict has been changed, only that potentially changing 
operations have been performed.  So it really depends on what Stef 
originally meant by changed, and perhaps what is meant by == :)

x = {'a', 3}
x['a'] = 3

Whether x has been changed by the second statement is the open 
question.  The above code would declare it has, but most people, when 
shown before and after copies of the dict, with declare it hasn't.

-- 
Glenn -- http://nevcal.com/
===========================
A protocol is complete when there is nothing left to remove.
-- Stuart Cheshire, Apple Computer, regarding Zero Configuration Networking




More information about the Python-list mailing list