Imagine the following project structure
app/
foo/
__init__.py
a.py
b.py
In a.py i have class A which uses class B from b.py file, and B class from b.py uses A class form a.py
if I write:
from foo.b import B
in a.py and
from foo.a import A
in b.py, the recursion occurs
How can I do properly import, without merging A and B in single file
Python doesn’t support circular imports, partly because they are usually a symptom of a flawed design.
What you can do is make
AandBself-contained and reference both of them from a third file, or alternatively, extract the shared structure into a third fileand reference that from both your modules. How exactly this is going to work highly depends on whatAandBare and why you think they should know of each other.For example, you could make
Ajust take a reference to an instance ofBvia its constructor, that way you won’t need an import:It gets a bit more complicated if inheritance is involved. In that case, you probably don’t want the superclass to know of the subclass, because that would violate the substitution principle.