How can I create a dict that sets a flag if it's been modified

Duncan Booth duncan.booth at invalid.invalid
Thu Jan 12 06:26:48 EST 2006


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.
> 
Detecting when a dictionary is updated is easy, just subclass dict and 
override the __setitem__ method.

Detecting when an object contained within the dictionary is mutated is 
effectively impossible.

If you are willing to compromise you can do something similar to the 
solution used in the ZODB (persistent object database): it marks an object 
as dirty when you rebind an attribute, but it doesn't attempt to catch 
mutation of contained objects. If you want a contained dictionary or list 
to be handled automatically by the persistence machinery you can use a 
PersistentDict or PersistentList object, otherwise you can use an ordinary 
dict/list and manually flag the container as dirty when you mutate it.

This leads to code such as (assuming self is the container):

...
    self.somelist.append(something)
    self.somelist = self.somelist

which isn't wonderful but mostly works. Of course:

    self.somelist += [something]

also has the desired effect.



More information about the Python-list mailing list