Stack Exchange
Split python code with classes refering to each other into multiple files without circular import error
I would like to split this code
class A:
    def __init__(self):
        self.b = B(self)

    @classmethod
    def foo(cls):
        pass


class B:
    def __init__(self, a):
        self.a = a
        A.foo()


if __name__ == "__main__":
    
    aa = A()
    bb = B(aa)

in two separated files
classA.py
from classB import B


class A:
    def __init__(self):
        self.b = B(self)

    @classmethod
    def foo(cls):
        pass

and classB.py
from classA import A


class B:
    def __init__(self, a):
        self.a = a
        A.foo()


if __name__ == "__main__":
    
    aa = A()
    bb = B(aa)

But this leads to an ImportError:
ImportError: cannot import name 'A' from partially initialized module 'classA' (most likely due to a circular import)

If one instead uses
classA.py
import classB


class A:
    def __init__(self):
        self.b = classB.B(self)

    @classmethod
    def foo(cls):
        pass

and classB.py
import classA


class B:
    def __init__(self, a):
        self.a = a
        classA.A.foo()


if __name__ == "__main__":
    
    aa = classA.A()
    bb = B(aa)

everything is fine. But this second version needs some significant changes to the code. Is there a way to split the content of two python classes referring to each other into two files, without the need to rename the methods?

Circular imports must be done by importing the whole module.  Trying to use from module import X should be avoided in these cases.  https://stackoverflow.com/q/744373/2532408 has a pretty good explanation.

Thank you for the link. That explains it really well. If you want, you can put this comment as an answer an I will accept it.

I think technically folks would consider this a duplicate, but I appreciate it.
