Why does the first statement return NameError
, while max
is available
>>> __builtin__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '__builtin__' is not defined
>>> max
<built-in function max>
>>> import __builtin__
>>> __builtin__.max
<built-in function max>
The builtins namespace associated with the execution of a code block is actually found by looking up the name
__builtins__
in its global namespace; this should be a dictionary or a module (in the latter case the module’s dictionary is used). 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.
So really it is looking up __builtins__
(since you are in the main module)
>>> __builtins__.max
<built-in function max>
But as mentioned above, this is just an alias for __builtin__
(which isn't part of the main module's namespace, although it has been loaded and referenced by __builtins__
).
__builtin__
is just a way to import/access the pseudo module in case you want to replace or add a function that is always globally available. You do not need to import it to use the functions. But __builtin__
itself does not exist on __builtin__
so it is not available without importing it first.
See the python docs for more information about this module.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With