简体   繁体   English

如何导入导入父模块的子模块?

[英]How to import child module which imports parent module?

I have my module structure as following:我的模块结构如下:

/parent
-- __init__.py
-- /child
---- __init__.py

I want to import child in parent and vice versa, IE:我想在parent中导入child ,反之亦然,IE:

/parent/ init .py: /父/初始化.py:

import child

/parent/child/ init .py: /父/子/初始化.py:

import parent

but when I do it I get the error No module named 'parent' in parent/child/__init__.py但是当我这样做时,我收到错误No module named 'parent' in parent/child/__init__.py

You are getting that error because of the circular dependency of modules in your code.由于代码中模块的循环依赖性,您会收到该错误。

When python tries to initialize your parent module it sees the import child statement, which leads the interpreter to the child module, (Notice that parent module is not initialized yet) now in the child module import parent line is encountered, but since the parent module is not initialized yet, the interpreter will fail with the error that it cannot find the parent module.当 python 尝试初始化您的parent模块时,它会看到import child语句,该语句将解释器引导到child模块,(注意parent模块尚未初始化)现在在子模块中遇到import parent行,但由于父模块尚未初始化,解释器将因找不到parent模块的错误而失败。

Ideally, you should fix the circular imports to solve this problem, But it can be overcome moving the import to a later stage instead of adding it at the top of the file.理想情况下,您应该修复循环导入来解决此问题,但是可以将导入移到稍后阶段而不是将其添加到文件顶部来克服它。 (For example: you can add the import statement in a method where you will be actually using the child module.) but it is not recommended to do this. (例如:您可以在实际使用子模块的方法中添加 import 语句。)但不建议这样做。

Add the parent path before importing it in child, this way parent module can be found在child中导入之前添加父路径,这样可以找到父模块

sys.path.append(os.path.abspath('..'))

Bad design alert不良设计警报

Circular imports problems can indicate bad design循环进口问题可能表明设计不佳

Solution解决方案

Your imports can't be both on top level.您的导入不能都在顶层。

# /parent/child/init.py:

import parent  # <-- top level

# /parent/init.py:

import .child  # <-- also top level

Common pattern is to move one of the import to place, where it is used (but not on top level, lul), eg:常见的模式是将其中一个导入移动到使用它的地方(但不是在顶层,lul),例如:

# /parent/child/init.py:

def dupa():
    import parent  # <-- not top level
    parent.foo()

See also也可以看看

Python circular importing? Python循环进口?

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

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