Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is __builtin__ made available at runtime?

Tags:

python

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>
like image 767
user2298943 Avatar asked Apr 27 '13 13:04

user2298943


2 Answers

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

like image 127
jamylak Avatar answered Nov 16 '22 03:11

jamylak


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

like image 4
ThiefMaster Avatar answered Nov 16 '22 03:11

ThiefMaster