简体   繁体   中英

Call exec inside a function - NameError

Why does this code raise NameError ?:

def func():
    exec("my_var = 42")
    print(my_var)
func()

There are many related questions, but I have not found a clear answer as to WHY. I don't want a workaround.

Also, I have noticed that the code works when I run:

exec("my_var = 42", globals(), globals())

But not really sure why.

The documentation for exec() states: "...if the optional parts are omitted [second and third arguments], the code is executed in the current scope.". The current scope is the func() function. Why can't I access my_var from this same scope?

The parser/compiler doesn't take the argument to exec() into account (since it could be a variable). So when it parses the function it doesn't see the assignment to my_var , so it treats it as a global variable. But the assignment in exec() will create a local variable. So the variable that was assigned is not the same one that it tries to print.

In addition, if you want changes to local variables to be visible, you have to pass the locals() dictionary explicitly. The [documentation] states:

Note: The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM