Track changes to lists and dictionaries in python?

后端 未结 5 1200
别跟我提以往
别跟我提以往 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:29

    My jsonfile module detects changes of (nested) JSON compatible Python objects. Just subclass JSONFileRoot to adapt change detection for your needs.

    >>> import jsonfile
    >>> class Notify(jsonfile.JSONFileRoot):
    ...   def on_change(self):
    ...     print(f'notify: {self.data}')
    ... 
    >>> test = Notify()
    >>> test.data = 1
    notify: 1
    >>> test.data = [1,2,3]
    notify: [1, 2, 3]
    >>> test.data[0] = 12
    notify: [12, 2, 3]
    >>> test.data[1] = {"a":"b"}
    notify: [12, {'a': 'b'}, 3]
    >>> test.data[1]["a"] = 20
    notify: [12, {'a': 20}, 3]
    

    Note that it goes on the proxy class way how e-satis advised, without supporting sets.

提交回复
热议问题