Consider the following code which uses Python's built-in funciton exec.
exec('a = 1')
print(a) # prints just fine
def foo():
exec('b = 2')
print(b) # NameError: name 'b' is not defined
foo()
When exec
is used in the global context to define a variable a
, the variable is available (e.g. print(a)
works); however, when exec
is used to define a variable, b
inside a function, the variable is not available (e.g. print(b)
causes a NameError
).
What's going on? Do I have to pass in the function's local context to exec
?