Python call function on dictionary member key change

Viewed 181

I have a class that looks kind of like this:

class MyClass:
    _properties: Dict[str, Any]

    @property
    def properties(self) -> Dict[str, Any]:
        ...

What I want to happen is I want to be notified when the dictionary is changed. So when a user does this:

obj = MyClass()

obj.properties['optimization'] = '-O3'

I would like some callback function to be called, ideally a callback function that has access to the key and value that were created/modified.

The only thing I can think of is inheriting dict and overriding __setitem__, but I am wondering if there is a nicer way to do this.

1 Answers

You can have a subclass that does what you want:

class MyClass:
    class Properties(dict):
        def __setitem__(self, key, value):
            print("Key {} was set to {}".format(key, value))
            super().__setitem__(key, value)

    _properties = Properties()

    @property
    def properties(self) -> Dict[str, Any]:
        return self._properties


m = MyClass()
m.properties['a'] = 12
print(m.properties)

output is:

Key a was set to 12
{'a': 12}
Related