0

I'm writing a library that involves codegen, and I'd like to test that the code I'm generating is doing what I expect it to. I want to generate the code, exec it, and then verify that the result is what I expect it to be. However, I'm finding that when I do this in my test functions, the variable I set in the generated code aren't visible. For instance, this works perfectly:

exec('a = 1')
print(a)

However, this fails with a NameError:

def demo():
    exec('b = 2')
    print(b)

demo()

What gives?

alexgolec
  • 26,898
  • 33
  • 107
  • 159
  • Does this answer your question? [exec() and variable scope](https://stackoverflow.com/questions/45535284/exec-and-variable-scope) & [How does exec work with locals?](https://stackoverflow.com/q/1463306/7942856) – PacketLoss May 14 '21 at 03:35
  • `With an explicit globals dict and no explicit locals dict, exec will use the same dict for both globals and locals` this sounds about right! – alexgolec May 14 '21 at 11:55

1 Answers1

1

Sadly from my understanding, you cannot use exec like that in a function. Instead you can store this in a dictionary as shown below.

def demo():
    varDict = {}
    exec("b=2", varDict)
    print(varDict["b"])
demo()

output

2
Buddy Bob
  • 5,829
  • 1
  • 13
  • 44