Consider the following code
g = {}
l = {}
exec("a = 1", g, l)
exec("""
def test():
print(a)
""", g, l)
l['test']()
This results in
$ python test.py
Traceback (most recent call last):
File "test.py", line 12, in <module>
l['test']()
File "<string>", line 3, in test
NameError: name 'a' is not defined
This only seems to happen when I use separate dictionaries for globals and locals. If I instead use g = l = {}
it works as expected.
Why is the variable defined by the first exec
not available in the function defined by the second exec
?
It's worth noting that the variable ends up in l
, not g
.
This seems similar to How does exec work with locals?, execpt it's not quite the same because here I am using a real dictionary for locals
.