gpt4 book ai didi

python - 为什么指定局部变量时 Python 3 exec() 会失败?

转载 作者:太空狗 更新时间:2023-10-29 18:02:49 24 4
gpt4 key购买 nike

以下在 Python 3 中执行时没有错误:

code = """
import math

def func(x):
return math.sin(x)

func(10)
"""
_globals = {}
exec(code, _globals)

但是如果我也 try catch 局部变量 dict,它会失败并返回 NameError:

>>> _globals, _locals = {}, {}
>>> exec(code, _globals, _locals)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-9-aeda81bf0af1> in <module>()
----> 1 exec(code, {}, {})

<string> in <module>()

<string> in func(x)

NameError: name 'math' is not defined

为什么会发生这种情况,如何在捕获全局变量和局部变量的同时执行此代码?

最佳答案

来自exec() documentation :

Remember that at module level, globals and locals are the same dictionary. If exec gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition.

您传入了两个单独的字典,但试图执行需要模块范围全局变量可用的代码。类中的 import math 会产生一个局部作用域属性,而您创建的函数将无法访问该属性,因为函数闭包不考虑类作用域名称。

参见 Naming and binding在 Python 执行模型引用中:

Class definition blocks and arguments to exec() and eval() are special in the context of name resolution. A class definition is an executable statement that may use and define names. These references follow the normal rules for name resolution with an exception that unbound local variables are looked up in the global namespace. The namespace of the class definition becomes the attribute dictionary of the class. The scope of names defined in a class block is limited to the class block; it does not extend to the code blocks of methods[.]

您可以通过尝试执行类定义中的代码来重现错误:

>>> class Demo:
... import math
... def func(x):
... return math.sin(x)
... func(10)
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in Demo
File "<stdin>", line 4, in func
NameError: name 'math' is not defined

只需传入一个字典即可。

关于python - 为什么指定局部变量时 Python 3 exec() 会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39647566/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com