how to detect if a dictionary has been modified ?

Glenn Linderman v+python at g.nevcal.com
Sun Nov 23 22:25:02 CET 2008


On approximately 11/23/2008 9:50 AM, came the following characters from 
the keyboard of Arnaud Delobelle:
> Glenn Linderman <v+python at g.nevcal.com> writes:
>
>   
>> 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}
>>     
>
> You mean x = {'a': 3}!
>   

Indeed I did, thanks for the correction.

>> 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.
>>     
>
> Good point.  What about
>
>   
>>>> d = {1: []}
>>>> d[1].append(2)
>>>>         
>
> Has d changed or not?
>   

Which just goes to show that the SDict implementation above is, as 
suspected by the author, incomplete for the purpose of detecting all 
changes to the dict, as well as detecting some that might not be 
perceived as changes.


-- 
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