'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, I.E.:
/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
Solution 1:[1]
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.
Solution 2:[2]
Add the parent path before importing it in child, this way parent module can be found
sys.path.append(os.path.abspath('..'))
Solution 3:[3]
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), eg:
# /parent/child/init.py:
def dupa():
import parent # <-- not top level
parent.foo()
See also
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Optimus |
Solution 2 | Hicham Zouarhi |
Solution 3 | D.Kallan |