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

Christian Tismer tismer at
Thu Jan 12 18:17:52 EST 2006

Steve Holden wrote:
> garabik-news-2005-05 at wrote:
>> sandravandale at 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.

IMHO, that's too much.

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

I think tracking whether a dict gets modified should in fact only
trace changes to the dict, not to elements contained in the dict.
So __repr__ is probably too much, and also not the intent.

I'd just overwrite __setitem__ for write access to the dict.
Enforcing tracking of all contents is hard (as you showed above)
and probably not really needed.

If further tracking is reasonable, then one would continue and
patch contained lists as well.

my 0.2 € - chris

Christian Tismer             :^)   <mailto:tismer at>
tismerysoft GmbH             :     Have a break! Take a ride on Python's
Johannes-Niemeyer-Weg 9A     :    *Starship*
14109 Berlin                 :     PGP key ->
work +49 30 802 86 56  mobile +49 173 24 18 776  fax +49 30 80 90 57 05
PGP 0x57F3BF04       9064 F4E1 D754 C2FF 1619  305B C09C 5A3B 57F3 BF04
      whom do you want to sponsor today?

More information about the Python-list mailing list