Python 导入阴影在 3.4.6 和 3.5.2 版本之间似乎有所不同:
$ cat time.py
from time import time
$ pyenv global 3.4.6
$ python -V
Python 3.4.6
$ python time.py
Traceback (most recent call last):
File "time.py", line 1, in <module>
from time import time
File "/home/vagrant/tmp/time.py", line 1, in <module>
from time import time
ImportError: cannot import name 'time'
$ pyenv global 3.5.2
$ python -V
Python 3.5.2
$ python time.py
$ echo no error
no error
问题 1:为什么是...那些东西?
问题 2:变更日志中是否有关于此的内容?我找不到任何东西...
最佳答案
When a module named
spam
is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file namedspam.py
in a list of directories given by the variablesys.path
.
(强调我的)
time
不是 Python 3.4 中的内置模块模块,但在 Python 3.5 中发生了变化:
me@temp:~$ python3.4 -c 'import sys; print("time" in sys.builtin_module_names)'
False
me@temp:~$ python3.5 -c 'import sys; print("time" in sys.builtin_module_names)'
True
您可以看到引入更改的补丁here (与 issue 5309 有关)。考虑到更新日志 mentions the issue 5309 ,但什么也没说。 time
模块,可以肯定地说更改是副作用并且是 CPython 的实现细节。
由于 time
不是 CPython 3.4 中的内置模块,而是 sys.path
中的第一个目录是当前脚本目录,from time import time
尝试从您的 time.py
文件导入 time
属性,但失败并抛出 导入错误
。
在 CPython 3.5 中,time
是 一个内置模块。根据上面的引述,运行 from time import time
成功导入内置模块,而无需在 sys.path
上搜索模块。
如果您隐藏标准库中的非内置模块,例如 inspect
,两个 CPython 版本都会引发相同的错误:
me@temp:~$ cat inspect.py
from inspect import signature
me@temp:~$ python3.4 -c 'import inspect'
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/home/me/inspect.py", line 1, in <module>
from inspect import signature
ImportError: cannot import name 'signature'
me@temp:~$ python3.5 -c 'import inspect'
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/home/me/inspect.py", line 1, in <module>
from inspect import signature
ImportError: cannot import name 'signature'
关于Python 导入阴影在 3.4.6 和 3.5.2 之间不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45199429/