Python 3 Trigger Callbacks on Implicit Value Changes

245 Views Asked by At

I want a callback to get called whenever a certain attribute of object A is changed.

I'm aware that this question is related to Observer Pattern and descriptors in Python. However, it seems descriptors could only detect explicit changes via dot access.

For instance:

class Observer(object):
    def __init__(self, callback=None):
        self.__callback = callback

    def __set_name__(self, owner, name):
        self.__name = name
    
    def __set__(self, obj, value):
        obj.__dict__[self.__name] = value
        self.trigger()
    
    def __get__(self, obj, type=None):
        return obj.__dict__.get(self.__name)
    
    def trigger(self):
        self.__callback()


def hello():
    print('hello')


class MyClass:
    data = Observer(hello)


a = MyClass()
a.data = [[1],2,3]
a.data.append(4)
a.data[0][0] = -1

In the above code, the callback is only called once for the initialization of the data. However, I want it to be called 3 times. I'm not tied to using descriptors but I do want the method to work on any data types, such as list, dict and etc.

0

There are 0 best solutions below