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?