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

Brian van den Broek broek at cc.umanitoba.ca
Thu Jan 12 04:42:21 EST 2006


sandravandale at yahoo.com said unto the world upon 12/01/06 03:15 AM:
> I can think of several messy ways of making a dict that sets a flag if
> it's been altered, but I have a hunch that experienced python
> programmers would probably have an easier (well maybe more Pythonic)
> way of doing this.
> 
> 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.
> 
> Thanks,
> -Sandra
> 

Hi Sandra,

here's one attempt. (I'm no expert, so wait for better :-)

 >>> class ModFlagDict(dict):
	def __init__(self, *args, **kwargs):
		super(ModFlagDict, self).__init__(*args, **kwargs)
		self.modified = False
	def __setitem__(self, key, value):
		self.modified = True
		super(ModFlagDict, self).__setitem__(key, value)

		
 >>> md = ModFlagDict(a=4, b=5)
 >>> md
{'a': 4, 'b': 5}
 >>> md.modified
False
 >>> md[3]=5
 >>> md
{'a': 4, 3: 5, 'b': 5}
 >>> md.modified
True
 >>>

It's broken in at least one way:

 >>> newmd = ModFlagDict(3=4, 1=5)
SyntaxError: keyword can't be an expression
 >>>

So, as it stands, no integers, floats, tuples, etc can be keys on 
initialization. I think that can be be worked around by catching the 
exceptions and setting the desired key-value pairs that way. But, it 
is almost 4am, and I also suspect there is a much better way I am not 
thinking of :-)

Best,

Brian vdB



More information about the Python-list mailing list