简体   繁体   中英

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/ init .py:

import child

/parent/child/ init .py:

import parent

but when I do it I get the error 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.

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.

Add the parent path before importing it in child, this way parent module can be found

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:

# /parent/child/init.py:

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

See also

Python circular importing?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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