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

Bengt Richter bokr at oz.net
Thu Jan 12 17:18:01 EST 2006


On Thu, 12 Jan 2006 18:28:54 +0000, Steve Holden <steve at holdenweb.com> wrote:

>garabik-news-2005-05 at kassiopeia.juls.savba.sk wrote:
>> sandravandale at yahoo.com wrote:
>> 
>>>It's important that I can read the contents of the dict without
>>>flagging it as modified, but I want it to set the flag the moment I add
>>>a new element or alter an existing one (the values in the dict are
>>>mutable), this is what makes it difficult. Because the values are
>>>mutable I don't think you can tell the difference between a read and a
>>>write without making some sort of wrapper around them.
>>>
>>>Still, I'd love to hear how you guys would do it.
>> 
>> 
>> if the dictionary is small and speed not important, you can wrap it 
>> in a class catching __getitem__ and __setitem__ and testing
>> if repr(self) changes.
>> 
>> 
>d = {1: [a, b],
>      2: [b, c]}
>
>d[1][0] = 3
>
>How would this work? __getitem__() will be called once, to get a 
>reference to the list, and so there's no opportunity to compare the 
>'before' and 'after' repr() values.
>
You are right, but OTOH the OP speaks of a "flagging" the dict as modified.
If she made e.g., "modified" a property of the dict subclass, then
retrieving the the "modified" "flag" could dynamically check current state repr
vs some prior state repr. Then the question becomes "modified w.r.t. what prior state?"

This lets the OP ask at any time whether the dict is/has_been modified, but it's not a basis
for e.g., a modification-event callback registry or such.

Regards,
Bengt Richter



More information about the Python-list mailing list