3

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?

Oliver
  • 27,510
  • 9
  • 72
  • 103
  • 1
    No. Assignment is not an operator in Python. The closest you can come is with the `__setitem__` trick you have done, and "assigning" by key into a custom object. Then you can do anything you want inside `__setitem__`. – PaulMcG Apr 16 '14 at 04:14
  • Do you want to *intercept* it and to assign it to the same `nsG` used for globals? that would change the behavior of the code you're `exec`ing in unpredicted ways, because you store globals and locals in the same dict. Besides, `globals` and `locals` behave differently in python... [You can't really tamper with `locals`](http://stackoverflow.com/a/8028772/2096752). – shx2 Apr 16 '14 at 05:22

0 Answers0