简体   繁体   中英

How is __builtin__ made available at runtime?

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>

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

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

You don't need to import __builtin__ in order for all the built-in names to be available. But you do need to import it in order for the name __builtin__ to be available in the scope of your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM