【发布时间】:2015-12-14 17:59:12
【问题描述】:
我想为我的项目使用这种结构:
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 上看到过其他类似结构的项目,但这似乎会导致各种问题。我如何让它发挥作用?
【问题讨论】:
-
兄弟包应该能够相互导入。所以引擎可以只导入核心。