Monitor Python class attributes (3)

Jan 28, 2019


The real solution from me is not looking pretty. In fact I don't think there is any good-looking solution out there. In this solution, I will consider the case where the attribute is a dictionary-like object. The most important thing that I have to consider then, is to modify the way the dictionary sets its items. To do this, I really have no options but to extend the dictionary class.

This is a very interesting piece of code. First I extend the dict class to udict, making its __setitem__ call very unique. This ensures that we can trigger any change detection whenever an item is changed.


Second, I have to make sure the udict object can call out a method in its outer class, namely ClassC._on_change(). To do this, I have to pass the object instantiated from the outer class into the inner class.


Third, I also have to make sure even if the dictionary reference is changed, the change detection is not triggered always; this is because the actual content of the dictionary may not get changed. This can be seen in the setter method for x.


Let's verify the results:

More tests after running the above code (notice that even if we change the dictionary reference, as long as the content is not changed, we are not triggering any change detection, which is correct!):

A final success!