Glenn Linderman <[EMAIL PROTECTED]> writes: > On approximately 11/23/2008 1:40 AM, came the following characters > from the keyboard of Steven D'Aprano: >> On Sun, 23 Nov 2008 01:18:17 -0800, bearophileHUGS wrote >>> Stef Mientki: >>> >>>> I would like to detect if a dictionary has been changed. So I would >>>> like to have a modified-flag. >>>> >>> A solution is of course to create a SDict class, that works like a >>> normal dict, and also watches for changes and has an extra boolean >>> attribute. >>> >> >> What does the S stand for? >> >> Untested and possibly incomplete: >> >> def factory(methodname, cls=dict, flag=True): >> def method(self, *args, **kwargs): >> self.modified = flag >> return getattr(cls, methodname)(self, *args, **kwargs) >> return method >> >> >> class SDict(dict): >> __init__ = factory('__init__', flag=False) >> __setitem__ = factory('__setitem__') >> __delitem__ = factory('__delitem__') >> clear = factory('clear') >> pop = factory('pop') >> popitem = factory('popitem') >> setdefault = factory('setdefault') >> update = factory('update') >> > > Interesting technique. I must point out, though, that it doesn't > indicate if a dict has been changed, only that potentially changing > operations have been performed. So it really depends on what Stef > originally meant by changed, and perhaps what is meant by == :) > > x = {'a', 3}
You mean x = {'a': 3}! > x['a'] = 3 > > Whether x has been changed by the second statement is the open > question. The above code would declare it has, but most people, when > shown before and after copies of the dict, with declare it hasn't. Good point. What about >>> d = {1: []} >>> d[1].append(2) Has d changed or not? -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list