Is there a way to automatically detect when a python object is being used (and possibly react to that)?
For example, let's say I have an object of type Foo. I did not write the class code for Foo, since it's coming from an external library.
I would like to "decorate" my object in such a way that, whenever one of its methods is used, or whenever its internal state (members) changes or is accessed, I get some logging info, like "Foo is being used".
I am using the "decorate" term to highlight that I wouldn't like to change all the interfaces where objects of type Foo are used. I would simply like to add some functionality to it.
Also I would avoid having to tinker with Foo's class code directly, i.e. by explicitly adding a print statement at the beginning of each of its methods (either way this wouldn't inform me of when its members are changing).
And I would not like to have to explicitly register my objects to some other objects, since that would be an "invasive" approach that would require to change the "client-side" code (the code that uses Foo objects) and it would be something that can be easily forgotten.
You can use monkey patching to achieve this. Re-assign one of the member functions on the object as a decorated function, which in turn calls the original function, along with some logging added.
For example:
Note, however, that monkey patching is best used only for unit testing, and not in production code. It can have unforeseen side-effects and should be used with caution.
As for identifying when a member variable's value changes, you can refer to this.
All of this does require you to modify the client side code -- if there's a way to achieve this without altering the client code, I don't know about it.