I have a problem concerning recursive import statements in a package. I saw plenty of posts on the subject, but I was not able to find a working solution. I reproduced a very minimal example isolating my problem.
The file organization in the package temp
is the following:
|-- __init__.py
|-- abstract.py
|-- a.py
|-- b.py
The file __init__.py
contains
from .a import A
from .b import B
The file abstract.py
contains
from abc import ABC, abstractmethod
class Abstract(ABC):
@abstractmethod
def __init__(self):
pass
The file a.py
contains
from .abstract import Abstract
from .b import B
class A(Abstract):
def __init__(self, string):
super().__init__()
self.string = string
def as_b(self):
return B(int(self.string))
The file b.py
contains
from .abstract import Abstract
from .a import A
class B(Abstract):
def __init__(self, integer):
super().__init__()
self.integer = integer
def as_a(self):
return A(str(self.integer))
I then created a file foo.py
to test the temp
package which contains
from temp import A, B
an_a = A("2")
a_b = B(4)
an_a_as_b = A.as_b()
a_b_as_a = B.as_a()
At the run time, I receive the error ImportError: cannot import name 'A'
. My understanding is that this is due to the recursive import statement (class A importing class B and vice-versa).
What is the best pythonic way to implement the classes A
and B
in the temp
package?