当我使用globals参数运行eval时,为什么不复制globals? [英] Why aren't globals copied when I run eval with a globals argument?

查看:96
本文介绍了当我使用globals参数运行eval时,为什么不复制globals?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于评估表达式中使用的全局变量,我很难理解eval()的行为.

I'm having difficulty understanding how eval() behaves regarding the globals used in the evaluated expression.

例如,以下脚本显示1:

x = 1
print eval('x')

以下脚本在NameError: name 'x' is not defined上失败:

x = 1
print eval('x', {})

但是,来自我的Python版本的eval()文档(强调我的):

However, from the documentation of eval() for my Python version (emphasis mine):

使用 globals locals 字典将 expression 参数解析并评估为Python表达式(从技术上来说是条件列表).全局和本地名称空间. 如果存在 globals 词典并且缺少'__builtins__',则在解析 exp 之前,将当前全局变量复制到 globals >.

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. If the globals dictionary is present and lacks ‘__builtins__’, the current globals are copied into globals before expression is parsed.

因此,据此,由于存在一个 globals 参数,并且确实缺少__builtins__,我希望将所有当前的全局变量-包括x-复制到表达式之前被评估;但显然并非如此.我想念什么?

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; but apparently that is not the case. What am I missing?

推荐答案

这似乎是一个错误.我不知道是文档中的错误还是实现中的错误,但是如果不存在__builtins__eval不会将当前的全局变量复制到globals中.而是它仅复制__builtins__ :

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. Rather, it only copies __builtins__:

if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
    if (PyDict_SetItemString(globals, "__builtins__",
                             PyEval_GetBuiltins()) != 0)
        return NULL;
}

Python错误跟踪器上我没有找到任何有关此的信息,并且仍然存在差异3.4和当前的dev分支,因此可能值得提交错误报告和建议的文档更正:

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:

如果存在 globals 词典且缺少'__builtins__',则在 expression 出现之前,将当前__builtins__复制到 globals 中.解析.

If the globals dictionary is present and lacks ‘__builtins__’, the current __builtins__ is copied into globals before expression is parsed.

这篇关于当我使用globals参数运行eval时,为什么不复制globals?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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