0

I have two classes with a method each taking objects of the respective other class as arguments. Now I want to use python type hints (PEP 484) on the methods, which results in the following code:

class A:
    def do(self, b: B) -> None:
        pass

class B:
    def do(self, a: A) -> None:
        pass

This will fail as at the first occurrence of B it is not yet defined. How can this stalemate be resolved?

V02460
  • 532
  • 5
  • 12

1 Answers1

0

To break the tie in this situation, you have to delay the parsing of the type to a time after the initial parsing of the module. For this case type hints give you the possibility to enclose types in quotes:

class A:
    def do(self, b: 'B') -> None:
        pass

class B:
    def do(self, a: A) -> None:
        pass

By using quotes the initial parsing of the document works without problems while the type information in the quotes can be evaluated when needed e.g. by a type checker. From PEP 484, Forward references:

When a type hint contains names that have not been defined yet, that definition may be expressed as a string literal, to be resolved later.

V02460
  • 532
  • 5
  • 12