我遇到了如何正确声明我编写的某些模块的导入的问题。
假设目录结构如下:
main_dir/
__init__.py
module_A
sub_dir/
__init__.py
module_B
module_C
因此模块 B 和 C 都位于相对于模块 A 的同一子目录中。
模块 B 导入 C。 模块 A 有时会导入 B。
因此,在模块 B 中,使用 import module_C
效果很好。
在模块 A 中,使用 import sub_dir.module_C
效果很好。
但是,在模块 A 中,使用 import sub_dir.module_B
导致 ImportError 没有名为 'module_C' 的模块
,因为 B 导入了 C。
我假设我可以将 B 更改为 import sub_dir.module_C
但我不想这样做,因为当我直接在 B 中启动而不是从 A 导入 B 时,它会中断.
处理此类问题的正确方法是什么?
最佳答案
这应该是您的应用程序文件结构。
app/
├── __init__.py
├── module_a.py
└── subdir
├── __init__.py
├── module_b.py
└── module_c.py
module_a.py
from subdir import module_b, module_c
然后,您将可以访问 module_a 中的所有模块。
如果您在 module_c 中导入 module_b 或在 module_b 中导入 module_c,您将获得 cyclic import问题。这是一个设计问题。您需要检查代码并重新考虑如何链接模块。
关于python - Python 中的相对导入问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29287540/