1

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.

asmeurer
  • 86,894
  • 26
  • 169
  • 240
  • 3
    The lesson to be learned is to not use `exec` or `eval`. – cs95 Sep 21 '17 at 22:22
  • 1
    Short answer, `globals` and `locals` must be the same mapping to act as if you were executing in the module-level scope. If you pass two different mappings, it is executed like a class definition. Just as if you define `a = classvar` in a class block, methods won't have access to `a` . – juanpa.arrivillaga Sep 22 '17 at 01:05
  • @juanpa.arrivillaga you should have written that as an answer. That's as clear as it gets. – asmeurer Sep 22 '17 at 02:15

0 Answers0