指定本地人时,为什么Python 3 exec()失败? [英] Why does Python 3 exec() fail when specifying locals?

查看:100
本文介绍了指定本地人时,为什么Python 3 exec()失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The following executes without an error in Python 3:

code = """
import math

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

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

但是,如果我也尝试捕获局部变量dict,它会失败,并显示NameError:

But if I try to capture the local variable dict as well, it fails with a 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

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

Why is this happening, and how can I execute this code while capturing both global and local variables?

推荐答案

来自 exec()文档:

请记住,在模块级别,全局变量和局部变量是同一词典.如果exec获得两个单独的对象作为 globals locals ,则代码将像嵌入在类定义中一样执行.

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会产生一个局部作用域属性,并且您创建的函数将无法访问该函数,因为函数闭包不考虑类作用域名称.

You passed in two separate dictionaries, but tried to execute code that requires module-scope globals to be available. import math in a class would produce a local scope attribute, and the function you create won't be able to access that as class scope names are not considered for function closures.

请参见 命名和绑定 在Python执行模型参考中:

See Naming and binding in the Python execution model reference:

在名称解析的上下文中,类定义块和exec()eval()的参数是特殊的.类定义是可以使用和定义名称的可执行语句.这些引用遵循通常的名称解析规则,但在全局命名空间中查找未绑定的局部变量.类定义的名称空间成为该类的属性字典.在类块中定义的名称范围仅限于该类块.它不会扩展到方法的代码块[.]

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[.]

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

You can reproduce the error by trying to execute the code in a class definition:

>>> 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 3 exec()失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆