0

Here is my code:

def main():
    exec('a = 1')
    print(a)


main()

It returns NameError: name 'a' is not defined

Of course, if I typed a = 1 instead of exec('a = 1'), the code works perfectly.

Even weirder, if I copy the above code to the Python interactive console and run it, it works. However, running it as a file returns the aforementioned error.

My guess is that using exec() only assigns a local variable local to inside the exec(). However, that makes little to no sense and makes exec() useless, as I imagine batch assignment for variables would be one of the most common uses. It also doesn't explain why the code runs in the console but not as a file.

  • There are very few "common uses" for `exec. It is dangerous, and as a rule should be avoided. There is almost ALWAYS a better way to do it. – Tim Roberts Nov 24 '22 at 04:06

0 Answers0