I want to be able to intercept the assignment of variables inside a function and execute my own code. I tried to create a custom dict as follows:
class userdict(dict): def __setitem__(self, key, value): print 'run my code' dict.__setitem__(self, key, value)
If I execute code using this as a global dict, then my custom code will run every time a variable is assigned. eg:.
UserDict = userdict() exec 'x = 1' in UserDict
But if my code is inside a function, it does not work:
code = """ def foo(): global x x = 1 """ exec code in UserDict UserDict['foo']()
In this case, an โxโ is assigned, but my custom code does not start. I assume that inside the function, the global dict changes somehow without calling setitem. It's right? Is there a way to intercept variable assignments inside a function and execute custom code?
I want to do this in order to synchronize some objects available inside the function with other objects in my program. In the case of words, when a function assigns to certain variables, this change should apply to other variables in my program.
source share