How do i detect or capture change of value of a global variable in python
variable = 10
print(variable)
variable = 20
# Detect changes to the value using a signal to trigger a function
UPDATE AST docs - GOOD INTRO https://greentreesnakes.readthedocs.io/en/latest/
To my knowledge, it is not possible to generically capture the assignment of a global symbol in Python (At least in CPython where globals are stored in a
dict
in themodule
object, both are C types that cannot be monkey patched).Here's a simple workaround that's a bit of a compromise. Use a wrapper object to store your monitored variables, and define
__setattr__
to do whatever you want to do before (or after) setting an attribute.The compromise of course is that now instead of writing something like:
You must now write:
How about instrument the bytecode to add a print statement before each statement that stores to the global variable. Here is an example:
instr_monitor_var
can instrument a functiontest
so the global variablea
will be printed out when its value is changed. Let me know if this works. Thanks!