how to detect if a dictionary has been modified ?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Nov 23 04:40:10 EST 2008


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')



-- 
Steven



More information about the Python-list mailing list