Reading the answer to the question, What's the difference between globals(), locals(), and vars()?, The following explanation was given for how locals()
works:
if locals() is called inside a function it constructs a dictionary of the function namespace as of that moment and returns it -- any further name assignments are not reflected in the returned dictionary, and any assignments to the dictionary are not reflected in the actual local namespace
In a comment, it was mentioned that
The part "and any assignments to the dictionary are not reflected in the actual local namespace" might be worded a bit to definite.
linking to the following code:
def f():
exec "pass"
locals()["x"] = 42
print(x)
f()
This returns 42
(at least in CPython 2.7). Without the line exec "pass"
python throws a NameError
because it can't find 'x'
. This fits with the definition that changes to the dictionary returned by locals()
inside a function are not reflected in the namespace. Why does adding the line exec "pass"
allow these changes to be reflected? Is this somehow tricking python into thinking it has excited the function?