C Python: Running Python code within a context
Python doesn't actually copy outer-scope locals into inner-scope locals; the documentation for locals
states:
Free variables are returned by locals() when it is called in function blocks, but not in class blocks.
Here "free" variables refers to variables closed over by a nested function. It's an important distinction.
The simplest fix for your situation is just to pass the same dict object as globals
and locals
:
code = """myvar = 300def func(): return myvarfunc()"""d = {}eval(compile(code, "<str>", "exec"), d, d)
Otherwise, you can wrap your code in a function and extract it from the compiled object:
s = 'def outer():\n ' + '\n '.join(code.strip().split('\n'))exec(compile(s, '<str>', 'exec').co_consts[0], {}, {})