I want to declare a function dynamically, and I want to wrap any access to global variables OR alternatively determine which variables are free, and wrap any access to free variables.
I play with code like this:
class D: def __init__(self): self.d = {} def __getitem__(self, k): print "D get", k return self.d[k] def __setitem__(self, k, v): print "D set", k, v self.d[k] = v def __getattr__(self, k): print "D attr", k raise AttributeError globalsDict = D() src = "def foo(): print x" compiled = compile(src, "<foo>", "exec") exec compiled in {}, globalsDict f = globalsDict["foo"] print(f) f()
This leads to the output:
D set foo <function foo at 0x10f47b758> D get foo <function foo at 0x10f47b758> Traceback (most recent call last): File "test_eval.py", line 40, in <module> f() File "<foo>", line 1, in foo NameError: global name 'x' is not defined
What I want will somehow catch access to x with my dictate-like wrapper D How can i do this?
I don't want to predefine all global variables (in this case x ), because I want them to be lazily loaded.
source share