I’m writing a Python package in which there are a lot of units (classes, functions…) that are referencing each other. I face problems with circular imports.
How to solve something like that:
a.py:
from .b import B
from .c import C
@dataclass
class A:
b: B = field(default_factory=B)
c: C = field(default_factory=C)
b.py:
from .a import A
from .c import C
@dataclass
class B:
a: A = field(default_factory=A)
c: C = field(default_factory=C)
c.py:
from .a import A
from .b import B
@dataclass
class C:
a: A = field(default_factory=A)
b: B = field(default_factory=B)
The above code will lead to circular imports. I know I can solve them by putting all classes into one file. But there is a lot of code, and if I put all classes into one file each time I have this problem, then I have would very big files, and I prefer to split it into many files, for better programming experience. What would be the best way to solve that?
What I tried:
-
I tried putting names of the classes in
'
(apostrophes). But that doesn’t work fordeafult_factory
. -
I tried using
import
instead, but I can’t figure out how to do relative imports withimport
keyword. Something like that:import .a
didn’t work.