Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call exec inside a function - NameError

Tags:

python

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?

like image 837
Manuel Ruiz Avatar asked Aug 03 '26 10:08

Manuel Ruiz


1 Answers

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.

like image 133
Barmar Avatar answered Aug 06 '26 00:08

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!