Python: What's the difference between __builtin__ and __builtins__?

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

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

__builtins__ can be set to a user-created dictionary to create a weak form of restricted execution.

CPython implementation detail: Users should not touch __builtins__; it is strictly an implementation detail. Users wanting to override values in the builtins namespace should import the __builtin__ (no 's') module and modify its attributes appropriately. The namespace for a module is automatically created the first time a module is imported.

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


You should use __builtin__ in your programs (in the rare cases that you need it), because __builtins__ is an implementation detail of CPython. It may either be identical to __builtin__, or to __builtin__.__dict__, depending on the context. As the documentation says:

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

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

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

Apparently the use of __builtins__ is for performance - it gives direct access to __builtin__.__dict__ when used in a non-main module, and therefore removes one level of indirection.


__builtin__ is a module containing the built-in functions and types. The fact that a name __builtins__ is available containing 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.