简体   繁体   English

Python中相对导入的问题

[英]Issue With Relative Imports In Python

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. 因此,模块B和C相对于模块A都在同一子目录中。

Module B imports C. Module A sometimes imports B. 模块B导入C。模块A有时导入B。

So, in Module B, using import module_C works fines. 因此,在模块B中,使用import module_C可以正常工作。

And in Module A, using import sub_dir.module_C works fine. 在模块A中,使用import sub_dir.module_C可以正常工作。

However, in Module A, using import sub_dir.module_B causes an ImportError no module named 'module_C' because B imports C. 但是,在模块A中,使用import sub_dir.module_B会导致ImportError no module named 'module_C'因为B会导入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. 我以为我可以将B更改为import sub_dir.module_C但我不想这样做,因为那样一来,当我直接从B开始而不是从A导入B时,它将import sub_dir.module_C

What's the correct way(s) to handle this sort of issue? 解决此类问题的正确方法是什么?

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 module_a.py

from subdir import module_b, module_c

Then, you will have access to all modules from module_a . 然后,您将可以从module_a访问所有模块。

If you import module_b in module_c or module_c in module_b you will have an cyclic import issue. 如果在module_c中导入module_b或在module_b中导入module_c ,则将出现循环导入问题。 This is a design question. 这是一个设计问题。 You need to review your code and rethink how to link modules. 您需要检查代码并重新考虑如何链接模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM