1

I have to Python classes that have instances of each other as properties

class A:
    def __init__(self, b: B) -> None:
        self.b = a

class B:
    def __init__(self, a: A) -> None:
        self.a = a

This works fine if those classes are defined in the same file, but in my case they're both quite large and I would like to move them to separate files. However if I do this I would I have to import B into a.py and A into b.py, which will cause a circular import error. Does anyone know of a patter that I can use to have A and B in separate files, maintain type hinting, and run into a circular import error?

mdornfe1
  • 1,982
  • 1
  • 24
  • 42

1 Answers1

3

Yes. Python ignores type hints in quotes:

class A:
    def __init__(self, b: 'B') -> None:
        self.b = a
class B:
    def __init__(self, a: 'A') -> None:
        self.a = a
Anonymous
  • 11,748
  • 6
  • 35
  • 57