简体   繁体   English

在函数内调用 exec - NameError

[英]Call exec inside a function - NameError

Why does this code raise NameError ?:为什么这段代码会引发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.有很多相关的问题,但我还没有找到关于 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.". exec()文档指出:“...如果省略了可选部分 [第二个和第三个参数],则代码将在当前范围内执行。”。 The current scope is the func() function.当前作用域是func()函数。 Why can't I access my_var from this same scope?为什么我不能从同一范围访问my_var

The parser/compiler doesn't take the argument to exec() into account (since it could be a variable).解析器/编译器不考虑exec()的参数(因为它可能是一个变量)。 So when it parses the function it doesn't see the assignment to my_var , so it treats it as a global variable.因此,当它解析函数时,它看不到对my_var的赋值,因此将其视为全局变量。 But the assignment in exec() will create a local variable.但是exec()中的赋值会创建一个局部变量。 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.此外,如果您希望对局部变量的更改可见,则必须显式传递locals()字典。 The [documentation] states: [文档] 指出:

Note: The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted.注意:默认locals的行为如下面函数locals()所述:不应尝试修改默认locals字典。 Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns.如果您需要在函数exec()返回后查看代码对局部变量的影响,请传递显式局部变量字典。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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