How to override __setitem__ for a function's globals dict?
问题 I want to be able to intercept variable assignments within a function and execute custom code. I have tried creating a custom dict as follows: class userdict(dict): def __setitem__(self, key, value): print 'run my code' dict.__setitem__(self, key, value) If I exec code using this as the global dict, then my custom code will run on each variable assignment. e.g.: UserDict = userdict() exec 'x = 1' in UserDict #outputs 'run my code' But if my code is inside a function, it doesn't work: code = "