Python: What is the difference between __builtin__ and __builtins__?

Today I encoded and noticed something. If I open a new interpreter session (IDLE) and check what is defined using the dir function, I get the following:

 $ 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 

Pay attention to the last line.

So my question is:

  • Is any alias of another?

  • Are the guys from Python planning to get rid of one of them?

  • What should I use for my own programs?

  • What about Python 3?

  • Any information is valuable!

Important:

I am using Python 2.7.2+ on Ubuntu.

+54
python language-design python-module
Jun 24 2018-12-12T00:
source share
4 answers

Straight from python documentation: http://docs.python.org/reference/executionmodel.html

By default, when the __main__ __builtins__ module has a built-in __builtin__ module (note: no 's'); when in any other module, __builtins__ is an alias for the __builtin__ dictionary.

__builtins__ can be installed in a user dictionary to create a weak form of limited execution.

CPython implementation details: Users should not touch __builtins__ ; this is strictly an implementation detail. users to override the values ​​in the builtins namespace should import __builtin__ (no 's') module and change its attributes accordingly. The namespace for the module is automatically created the first time the module is imported.

Note that in Python3 the __builtin__ module has been renamed to builtins to avoid some confusion.

+48
Jun 24 '12 at 22:10
source share

You should use __builtin__ in your programs (in rare cases, when necessary), because __builtins__ is a detail of the implementation of CPython. It can be either identical to __builtin__ or __builtin__.__dict__ , depending on the context. As the documentation says:

Most modules are named __builtins__ (note the 's'), available as part of their global variables. The value of __builtins__ usually either this module or the value of this modal attribute __dict__ . Since this is an implementation detail, it cannot be used by alternative Python implementations.

In Python 3, __builtin__ was renamed to builtins , and __builtins__ remains the same (so you should only use builtins in Python 3).

Guido wanted to combine __builtin__ and __builtins__ , as you can see here ("Having __builtins__ and __builtin__ both clearly a bad idea."), But apparently, nothing came of it.

Apparently using __builtins__ for performance - this gives direct access to __builtin__.__dict__ when used in a non-core module and therefore removes one level of indirection.

+18
Jun 24 '12 at 22:11
source share

__builtin__ is a module that contains built-in functions and types. The fact that the name __builtins__ available with the same things is an implementation detail. In other words, if you need to use one of them, do import __builtin__ , and then use __builtin__ . See the documentation .

+7
Jun 24 2018-12-12T00:
source share

You can understand them as the following code. when running cpython, cpython load __builtin__ modules into the global namespace

import __builtin__ as __builtins__

+2
Jan 14 '13 at 9:58
source share



All Articles