Monitor Python class attributes (1)
Jan 26, 2019
For some reasons, I came across the following questions when I was doing my work: how do you monitor changes of the attributes in a specific Python class? This is a very tricky problem, since the first answer I came up with was not doing exactly what I want. I am going to split this topic into several notes; today I am only going to show the first one.
It seems like a simple getter and setter function should do what I want. So I had the following class:
To test the above code, let's consider:
Let's check the results:
This seems to be correct. However, it is not going to achieve my goal. Why? Consider the attribute itself is a dictionary (in fact I wanted to monitor a Python dictionary).
Results:
You can see when a new key is added to the dictionary, no change is detected. This is natural since the attribute itself is considered a mutable object and its reference is not changed. We will try a few more techniques later.