我想为我的项目采用这种结构:
requirements.txt
README.md
.gitignore
project/
__init__.py
project.py
core/
__init__.py
base.py
engines/
__init__.py
engine1.py
engine2.py
utils/
__init__.py
refine_data.py
whatever.py
应用程序从 project/project.py
运行。但是,在使用相对或绝对导入时,我经常遇到导入错误。
两个引擎都需要从project.core.base
导入,utils也需要从project.core.base
导入,还有project.py
(运行的主文件)需要能够从 engines
导入。
绝对导入不起作用:
# engines/engine1.py
from project.core.base import MyBaseClass
给出了错误:
ImportError: No module named project.core.base
但如果我改为尝试相对导入
# engines/engine1.py
from ..core.base import MyBaseClass
我得到:
ValueError: Attempted relative import beyond toplevel package
我在 Github 上看到过类似结构的其他项目,但这似乎会导致各种问题。我如何让它发挥作用?
最佳答案
查看您的 sys.path
。顶级 project
目录很可能在 python 路径中,它会看到您的子包(即 utils
、engines
等。 ) 作为单独的包,这就是为什么它给你一个错误,你在做相对导入时试图从你的包外部导入,而绝对导入不起作用,因为它找不到顶级项目目录,因为它不在任何 python 路径。
顶级项目目录上方目录是需要添加到python路径的目录。
例如
/path/is/here/project/core/...
# Add this to the PYTHONPATH
/path/is/here
关于Python导入结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34273598/