【问题标题】:Where is the __builtin__ module in Python3? Why was it renamed?Python3 中的 __builtin__ 模块在哪里?为什么改名了?
【发布时间】:2012-01-28 19:07:01
【问题描述】:

我很好奇__builtin__ 模块以及它是如何使用的,但是我在Python3 中找不到它!为什么要搬家?

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__
>>>

【问题讨论】:

    标签: python


    【解决方案1】:

    __builtin__ 模块在 Python3 中被重命名为 builtins

    此更改解决了普通 Python 开发人员的 2 个困惑。

    • '__builtins__' 还是'__builtin__' 在全局命名空间中? 该死的!
    • __builtin__special method name 还是模块?我不能 告诉。

    这种混淆主要是因为违反了pep8 约定。此外,模块上缺乏多元化也阻碍了沟通。 Guido 必须从http://mail.python.org/pipermail/python-ideas/2009-March/003821.html 解释以下内容的长度很好地说明了这两者:

    [CPython] 查看全局变量,其中包含一个特殊的魔法条目 __builtins__(带有's')这是查找内置函数的字典。当这个 dict 和 default 是同一个对象时 内置字典(__builtin__.__dict__ 其中__builtin__ -- 没有's' - 是定义内置函数的模块)它给出 你的主管权限;…

    例如,

    Python2.7

    >>> import __builtin__
    >>> vars(globals()['__builtins__']) is vars(__builtin__)
    True
    >>> 
    

    Python3.2

    >>> import builtins
    >>> vars(globals()['__builtins__']) is vars(builtins)
    True
    >>>
    

    相关资源

    其他名称更改 - http://docs.pythonsprints.com/python3_porting/py-porting.html#name-changes

    关于如何在名称解析中使用 __builtins__ 的简要说明 - __builtin__ module in Python

    【讨论】:

    • 它如何解决内置 vs bultins 问题?如果我不确定是否有 s,我仍然会弄错
    • @blues 如果你尝试import builtin,就会出现一个错误ImportError: No module named 'builtin' ,这很容易理解。此外,该模块现在是well documented
    【解决方案2】:

    删除所有pyc文件并再次运行 就这些

    【讨论】:

      猜你喜欢
      • 2011-06-26
      • 1970-01-01
      • 1970-01-01
      • 2015-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-01
      • 2016-04-10
      相关资源
      最近更新 更多