gpt4 book ai didi

python - 为什么 eval 尝试在 __builtins__ 上下标?

转载 作者:太空宇宙 更新时间:2023-11-04 02:20:55 24 4
gpt4 key购买 nike

>>> eval('potato', {'__builtins__': None})
NameError: name 'potato' is not defined

Python 2。有道理。

>>> eval('potato', {'__builtins__': None})
TypeError: 'NoneType' object is not subscriptable

Python 3. eval 如何/为什么尝试下标 None?我希望这里出现相同的 NameError,或者可能是 AttributeError: 'NoneType' object has no attribute 'potato'

通过 Python eval error 遇到

最佳答案

来自 eval(expression, globals=None, locals=None) docs :

If the globals dictionary is present and lacks ‘__builtins__’, the current globals are copied into globals before expression is parsed. This means that expression normally has full access to the standard __builtin__ module and restricted environments are propagated.

但是您在全局字典中将 __builtins__ 设置为 None,因此您的代码将计算为 None['potato'],这导致到:

TypeError: 'NoneType' object is not subscriptable

编辑:

如果在 __builtins__ 中找不到变量,Python2.7 将引发 NameError - source code . NAME_ERROR_MSG 定义为:

#define NAME_ERROR_MSG \
"name '%.200s' is not defined"

Python3 打印不同的消息 - 请参阅 source - PyObject_GetItem 不会引发 KeyError 但会引发 TypeError 因此字符串的格式不同,在这种情况下 TypeError: 'NoneType' 对象是不可订阅

在 CPython 中,名称 __builtins__ 可以绑定(bind)到模块或字典。即documented under the execution model :

The builtins namespace associated with the execution of a code block is actually found by looking up the name __builtins__ in its global namespace; this should be a dictionary or a module (in the latter case the module’s dictionary is used).

关于python - 为什么 eval 尝试在 __builtins__ 上下标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51660505/

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