Python:__builtin__和__builtins__有什么区别?

我今天正在编码,发现了一些东西。 如果我打开一个新的解释器会话(空闲),并检查与dir函数定义了什么,我得到这个:

 $ python >>> dir() ['__builtins__', '__doc__', '__name__', '__package__'] >>> dir(__builtins__) ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip'] >>> import __builtin__ ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip'] >>> dir(__builtin__) == dir(__builtins__) # They seem to have the same things True 

请注意最后一行。

所以,我的问题是:

  • 是另一个的别名吗?

  • Python家伙计划摆脱其中之一吗?

  • 我应该为自己的程序使用什么?

  • 那么Python 3呢?

  • 任何信息都是有价值的

重要:

我在Ubuntu上使用Python 2.7.2+。

直接从python文档: http : //docs.python.org/reference/executionmodel.html

默认情况下,在__main__模块中, __builtins__是内置模块__builtin__ (注意:不是's'); 当在其他模块中时, __builtins____builtin__模块本身的字典的别名。

可以将__builtins__设置为用户创build的字典来创build受限执行的弱forms。

CPython实现细节:用户不应该触摸__builtins__ ; 这是严格的实施细节。 想要覆盖内build命名空间中的值的用户应该import __builtin__ (no's')模块并适当修改其属性。 模块的命名空间在第一次导入模块时自动创build。

请注意,在Python3中,模块__builtin__已被重命名为builtins以避免一些混淆。

您应该在程序中使用__builtin__ (在极less数情况下,您需要它),因为__builtins__是CPython的实现细节。 它可能与__builtin__相同,或者与__builtin__.__dict__ ,具体取决于上下文。 正如文档所述 :

大多数模块的名字__builtins__ (注意's')作为其全局variables的一部分提供。 __builtins__的值通常是这个模块或者这个模块的__dict__属性的值。 由于这是一个实现细节,它可能不会被替代的Python实现使用。

在Python 3中, __builtin__已经被重命名为builtins ,并且__builtins__保持不变(所以你应该只在Python 3中使用builtins )。

Guido想要团结__builtin____builtins__ ,正如你在这里所看到的(“有__builtins____builtin__两者显然是一个坏主意”),但是显然没有任何结果。

显然使用__builtins__是为了提高性能 – 当在非主模块中使用__builtin__.__dict__时,可以直接访问它,因此可以删除一个间接级别。

__builtin__是一个包含内置函数和types的模块。 包含相同事物的名称__builtins__可用的事实是实现细节。 换句话说,如果您需要使用其中之一,请import __builtin__ ,然后使用__builtin__ 。 请参阅文档 。

你可以像下面的代码一样理解这些。 当cpython启动时,cpython将__builtin__模块加载到全局命名空间中

import __builtin__ as __builtins__