问题描述
我对 __builtin__
模块及其使用方式很好奇,但我在 Python3 中找不到它!为什么要搬家?
Python 2.7
>>>导入 __builtin__>>>Python 3.2
>>>导入 __builtin__回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中导入错误:没有名为 __builtin__ 的模块>>>__builtin__
模块在 Python3 中更名为 builtins
.
此更改解决了普通 Python 开发人员的两个困惑来源.
- 是
'__builtins__'
还是'__builtin__'
位于全局命名空间中?该死的! - 是
__builtin__
一个 特殊方法名称 或一个模块?我不能告诉.
这种混淆主要是因为违反了pep8 约定.此外,模块上缺乏多元化也阻碍了沟通.Guido 必须从 http://mail.python.org/pipermail/python-ideas/2009-March/003821.html:
[CPython] 查看全局变量,其中包含一个特殊的魔法条目__builtins__
(带有一个s"),它是查找内置函数的字典.当这个 dict 与 default 是同一个对象时内置字典(即 __builtin__.__dict__
其中 __builtin__
--没有's' - 是定义内置函数的模块)它给出您的主管权限;...
例如
Python2.7
>>>导入 __builtin__>>>vars(globals()['__builtins__']) 是 vars(__builtin__)真的>>>Python3.2
>>>导入内置函数>>>vars(globals()['__builtins__']) 是 vars(builtins)真的>>>相关资源:
其他名称更改 - http://docs.pythonsprints.com/python3_porting/py-porting.html#name-changes
有关如何在名称解析中使用 __builtins__
的简洁说明 - __builtin__Python 中的模块
I was curious about the __builtin__
module and how it's used, but I can't find it in Python3! Why was it moved?
Python 2.7
>>> import __builtin__
>>>
Python 3.2
>>> import __builtin__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named __builtin__
>>>
The __builtin__
module was renamed to builtins
in Python3.
This change solves 2 sources of confusion for the average Python developer.
- Is it
'__builtins__'
or'__builtin__'
that is in the global namespace?Darn s! - Is
__builtin__
a special method name or a module? I can'ttell.
This confusion mainly arises because of the violation of pep8 convention. Also, the lack of pluralization on the module hinders communication as well. Both of these are greatly illustrated by the lengths Guido must go to explain the following from http://mail.python.org/pipermail/python-ideas/2009-March/003821.html:
For example,
Python2.7
>>> import __builtin__
>>> vars(globals()['__builtins__']) is vars(__builtin__)
True
>>>
Python3.2
>>> import builtins
>>> vars(globals()['__builtins__']) is vars(builtins)
True
>>>
Related resources:
Other name changes - http://docs.pythonsprints.com/python3_porting/py-porting.html#name-changes
For a succinct explanation of how __builtins__
is used in name resolution - __builtin__ module in Python
这篇关于Python3 中的 __builtin__ 模块在哪里?为什么改名了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!