通过 __builtins__ 访问内置函数

Access builtin functions by __builtins__

我有以下脚本:

a.py

print(__builtins__.max)
import b

和以下模块:

b.py

print(__builtins__.max)

python3 a.py 启动它们我得到:

<built-in function max>
Traceback (most recent call last):
  File "a.py", line 2, in <module>
    import b
  File "/home/antonio/Scrivania/b.py", line 1, in <module>
    print(__builtins__.max)
AttributeError: 'dict' object has no attribute 'max'

所以我不明白。为什么在脚本中 __builtins__ 被分配给内置模块而不是在模块中 __builtins__ 被分配给字典?

不要使用__builtins__;请改用 builtins module

__builtins__ 对象是您不应依赖的实现细节。来自 builtins 模块文档:

As an implementation detail, most modules have the name __builtins__ made available as part of their globals. The value of __builtins__ is normally either this module or the value of this module’s __dict__ attribute. Since this is an implementation detail, it may not be used by alternate implementations of Python.

注意我强调的地方;当您访问 __builtins__.

时,您可以拥有字典或模块对象

老实说?我无法想象当他们让 __builtins__ 在脚本和模块中表示不同的东西时他们在想什么。我正在使用 __builtins__ 从一个将自己的 ImportError 定义为 public API 的库中访问 built-in ImportError,它对我有用,直到今天。

我不知道确切的区别。我的 __builtins__.ImportError 在 Python 2.x 和 Python 3.x 的模块中工作。现在,随着代码中的一些上游更改,相同的构造完全像您的情况一样失败。我使用网络搜索找到了你的问题,我将回答可能遇到相同情况的其他人。

由于上述问题,您无法使用 __builtins__,并且您无法在 Python 2.x 中使用 builtins,但我设法使用 [=27 修复了该问题=]六个python模块.

from six.moves import builtins

这对我来说在 Python 2.x 和 Python 3.x 中都有效,并且它在 __builtins__ 失败的完全相同的地方工作。希望对您有所帮助。