什么是Python隐式相对导入

What is Python implicit relative import

在PEP8中--Python代码的样式指南

Explicit relative imports are an acceptable alternative to absolute imports

Implicit relative imports should never be used and have been removed in Python3.

什么是python隐式相对导入?

隐式导入是一种算法

Search up from current package directory until the ultimate package parent gets hit.
-- From https://www.python.org/dev/peps/pep-0328/#rationale-for-relative-imports

有人能详细解释一下吗?

在Python中移除3?

1
2
3
4
5
6
7
8
9
10
11
python2 -c 'import csv; print(csv)'
<module 'csv' from '/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/csv.pyc'>

$ touch csv.py

$ python2 -c 'import csv; print(csv)'
<module 'csv' from 'csv.pyc'>

# In python3 still search from current package
$ python3 -c 'import csv; print(csv)'
<module 'csv' from '/path_to/csv.py'>

为什么PEP-0008建议永远不要使用它?


当你说:

1
import foo

python 2将首先在调用者的目录中查找。python 3不会这样做,只会在通常的地方找到sys.path(PYTHONPATHsite-packages等)。

这意味着,如果您正在编写支持python 3的包,那么您应该在包中这样说:

1
import mypkg.foo

或者使用显式的相对导入:

1
from . import foo