When I run the code below, I get a NameError
:
def foo():
exec("data = [1, 2, 3]", globals(), locals())
return data
foo() # Returns an error:
# ---------------------------------------------------------------------------
# NameError Traceback (most recent call last)
# <ipython-input-24-617677c4ff0e> in <module>()
# 3 return data
# 4
# ----> 5 foo()
#
# <ipython-input-24-617677c4ff0e> in foo()
# 1 def foo():
# 2 exec("data = [1, 2, 3]")
# ----> 3 return data
# 4
# 5 foo()
#
# NameError: name 'data' is not defined
Even though the assignment seemed to work, and I can return it by manually indexing into the locals-namespace:
def bar():
exec("data = [1, 2, 3]")
return vars()["data"]
bar() # Returns [1, 2, 3]
How come?