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:55:33 EST 2006
Brian van den Broek said unto the world upon 12/01/06 03:42 AM:
> 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.
<snip>
> 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)
<snip>
> 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 :-)
Sorry for the self-reply, but I just realized my original code isn't
quite so bad as:
# class ModFlagDict as before
>>> mdict = ModFlagDict({42:"This will work", (7, 6):"Python comes
through, again!"})
>>> mdict
{42: 'This will work', (7, 6): 'Python comes through, again!'}
>>> mdict.modified
False
>>> mdict[42]=":-)"
>>> mdict
{42: ':-)', (7, 6): 'Python comes through, again!'}
>>> mdict.modified
True
>>>
I'll wager someone will point out a better way still, though.
Best,
Brian vdB
More information about the Python-list
mailing list