[英]Why aren't globals copied when I run eval with a globals argument?
I'm having difficulty understanding how eval()
behaves regarding the globals used in the evaluated expression. 我很难理解
eval()
在计算表达式中使用的全局变量的行为方式。
For example, the following script prints 1
: 例如,以下脚本打印
1
:
x = 1
print eval('x')
While the following script fails on NameError: name 'x' is not defined
: 以下脚本在
NameError: name 'x' is not defined
失败NameError: name 'x' is not defined
:
x = 1
print eval('x', {})
However, from the documentation of eval()
for my Python version (emphasis mine): 但是,从我的Python版本的
eval()
文档 (强调我的):
The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals dictionaries as global and local namespace.
表达式参数作为Python表达式(技术上讲,条件列表)被解析和评估,使用全局变量和本地字典作为全局和本地名称空间。 If the globals dictionary is present and lacks '__builtins__', the current globals are copied into globals before expression is parsed .
如果全局字典存在且缺少'__builtins__',则在解析表达式之前将当前全局变量复制到全局变量中 。
So according to this, since a globals argument is present and indeed lacks __builtins__
, I'd expect all the current globals - including x
- to be copied into it before the expression is evaluated; 所以根据这个,因为全局参数存在并且确实缺少
__builtins__
,所以我希望在计算表达式之前将所有当前的全局变量(包括x
复制到其中; but apparently that is not the case. 但显然事实并非如此。 What am I missing?
我错过了什么?
This appears to be a bug. 这似乎是一个错误。 Whether it's a bug in the documentation or the implementation, I don't know, but
eval
does not copy the current globals into globals
if __builtins__
is not present. 无论是文档中的错误还是实现中的错误,我都不知道,但如果
__builtins__
不存在, eval
不会将当前全局globals
复制到globals
。 Rather, it only copies __builtins__
: 相反, 它只复制
__builtins__
:
if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
if (PyDict_SetItemString(globals, "__builtins__",
PyEval_GetBuiltins()) != 0)
return NULL;
}
I didn't find anything about this on the Python bug tracker , and the discrepancy is still present in 3.4 and the current dev branch, so it may be worth submitting a bug report and a proposed documentation correction: 我没有在Python错误跟踪器上找到任何关于此的信息,并且差异仍然存在于3.4和当前的dev分支中,因此可能值得提交错误报告和建议的文档更正:
If the globals dictionary is present and lacks '
__builtins__
', the current__builtins__
is copied into globals before expression is parsed.如果全局字典存在且缺少'
__builtins__
',则在解析表达式之前将当前的__builtins__
复制到全局变量中 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.