In my Python Shell, deleting __name__
makes it become 'builtins'
. Although, checking with globals
confirms that I am not refering to __name__
from some global variable.
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> __name__
'__main__'
>>> del __name__
>>> __name__
'builtins'
>>> globals()[__name__]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'builtins'
My guess is that we are using it from some closure. How is this behaviour taking place?
All names are looked up first from local variables, then global variables, then __builtins__
, which is available everywhere. It's where all the built in functions are.
In[6]: __builtins__
Out[6]: <module 'builtins' (built-in)>
In[7]: __builtins__.__name__
Out[7]: 'builtins'
In[8]: __builtins__.len
Out[8]: <function len>
As you can probably guess from the __name__
, you're accessing the name of the builtins
module .
Whenever you access a variable and that variable isn't found in any closure, the local scope or the global scope, the lookup falls back to the builtins. This is why you can access things like min
or max
or type
even though they're not global variables:
>>> 'min' in globals()
False
>>> min
<built-in function min>
>>> __builtins__.min
<built-in function min>
The same thing happens with __name__
. Initially, there's a __name__
variable defined in the global scope:
>>> globals()['__name__']
'__main__'
But once that name is deleted with del __name__
, the lookup in the globals fails and falls back to the builtins - so you end up with the name of the builtins
module.
>>> del __name__
>>> __name__
'builtins'
>>> __builtins__.__name__
'builtins'
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.