Track changes to lists and dictionaries in python?

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

    Instead of monkey patching, you can create a proxy class:

    • Make a proxy class that inherit from dict/list/set whatever
    • Intercept attribute setting, and if the value is a dict/list/set, wrap it into the proxy class
    • In proxy class __getattribute__, make sure the method is called on the wrapped type, but take care of tracking before doing so.

    Pro:

    • no class alteration

    Con:

    • you are limited to a number of types you know and expect

提交回复
热议问题