Issue With Relative Imports In Python

眉间皱痕 提交于 2019-12-13 00:39:52

问题


I'm running into an issue with how to properly declare imports for some modules that I've written.

Suppose the follow directory structure:

main_dir/
 __init__.py
 module_A
    sub_dir/
     __init__.py
     module_B
     module_C

So that modules B and C are both in the same subdirectory relative to module A.

Module B imports C. Module A sometimes imports B.

So, in Module B, using import module_C works fines.

And in Module A, using import sub_dir.module_C works fine.

However, in Module A, using import sub_dir.module_B causes an ImportError no module named 'module_C' because B imports C.

I'm assuming that I could change B to import sub_dir.module_C but I don't want to do that because then it will break when I start directly in B rather than import B from A.

What's the correct way(s) to handle this sort of issue?


回答1:


This should be your app structure of files.

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

Then, you will have access to all modules from module_a.

If you import module_b in module_c or module_c in module_b you will have an cyclic import issue. This is a design question. You need to review your code and rethink how to link modules.



来源:https://stackoverflow.com/questions/29287540/issue-with-relative-imports-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!