Skip to content
Advertisement

Decorating a class to monitor attribute changes

I want to have classes that automatically send notifications to subscribers whenever one of their attributes change. So if I would write this code:

JavaScript

The output would be:

JavaScript

My question is how to implement the ChangeMonitor decorator class. In the above example I assume it will print a line indicating the changes of an attribute, but for useful purposes it could send notifications to subscribed objects.

Advertisement

Answer

You’d have to add a __setattr__() method:

JavaScript

This should handle existing __setattr__ hooks as well. The _sentinel is used to allow None as the old value too.

Demo:

JavaScript
Advertisement