I've been playing around with intercepting global assignment in Python:
class MyDict(dict):
def __setitem__(self, k, v):
print "intercepted assignment to ", k
super(MyDict, self).__setitem__(self, k, v)
nsG = MyDict()
exec('a=10', nsG)
This prints "intercepted assignment to a". Cool! However, this does not work inside a function:
def f():
# global a
a = 10
exec("f()", nsG)
There, assignment to a
is not intercepted (because by default, assignments within a function are local to that function: a
is local to f
so nsG
is not involved; if I uncomment the global a
statement in f
, then the assignment is intercepted, as one would expect).
Is there a way of intercepting local assignment within a function?