Track changes to lists and dictionaries in python?

后端 未结 5 1212
别跟我提以往
别跟我提以往 2020-12-14 03:04

I have a class where the instances of this class needs to track the changes to its attributes.

Example: obj.att = 2 would be something that\'s easily tr

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-14 03:41

    You can also wrap the dictionary or list methods you want to track and make sure you do what you want inside the wrapper. Here is a dict example:

    from functools import wraps
    
    def _setChanged(func):
        @wraps(func)
        def wrappedFunc(self, *args, **kwargs):
            self.changed = True
            return func(self, *args, **kwargs)
        return wrappedFunc
    
    def _trackObjectMethods(calssToTrack):
        for methodName in dir(calssToTrack):
            if methodName in calssToTrack._destructive:
                setattr(calssToTrack, methodName, _setChanged(getattr(calssToTrack, methodName)))
    
    class Dictionary(dict):
        _destructive = ('__delitem__', '__setitem__', 'clear', 'pop', 'popitem', 'setdefault', 'update')
    
        def __init__(self, *args, **kwargs):
            self.changed = False
            super().__init__(*args, **kwargs)
    
    _trackObjectMethods(Dictionary)
    
    d = Dictionary()
    print(d.changed)
    d["1"] = 'test'
    print(d.changed)
    d.changed = False
    print(d.changed)
    d["12"] = 'test2'
    print(d.changed)
    

    As you can see if any items of the dictionary changes, the custom variable that I added to my custom Dictionary object will be set to True. This way I can tell if the object has changes since the last time I had set the changed variable to False.

提交回复
热议问题