>>> 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).
