0

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?

Hypnotoad
  • 173
  • 1
  • 6
  • 1
    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. – Marcel Wilson Aug 11 '22 at 15:36
  • 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. – Hypnotoad Aug 15 '22 at 06:17
  • I think technically folks would consider this a duplicate, but I appreciate it. – Marcel Wilson Aug 15 '22 at 15:24

0 Answers0