user3525381
user3525381

Reputation: 227

Rig a monitor for a variable to run a function whenever it changes?

So, I have two objects that represent a user's settings and a user's data. What I'd like to do is have some kind of monitor going that will save the settings/data whenever I change them in my code. I could surely just include a function call after every change, but just as an interesting concept, I was wondering if such an idea was possible.

The first solution that comes to mind is spinning off a thread that will make a copy of the objects and then loop a timer, each time checking if the objects differ from the copy.

Would such a plan be feasible? Is there a better way? The data object could theoretically be kind of large because it stores some cached images and lots of text; would I be causing noticeable performance issues by doing this?

Upvotes: 1

Views: 100

Answers (1)

steveha
steveha

Reputation: 76715

There is no way in Python to monitor changes to a simple variable. However, you can do exactly what you want to member variables in a class instance.

Look up "property descriptors".

Here's a nice explanation: http://nbviewer.ipython.org/urls/gist.github.com/ChrisBeaumont/5758381/raw/descriptor_writeup.ipynb

Upvotes: 1

Related Questions