Class name forward references

Python does not allow references to a class object before the class isdefined. Thus this code does not work as expected:

  1. def f(x: A) -> None: # Error: Name A not defined
  2. ...
  3.  
  4. class A:
  5. ...

In cases like these you can enter the type as a string literal — thisis a forward reference:

  1. def f(x: 'A') -> None: # OK
  2. ...
  3.  
  4. class A:
  5. ...

Of course, instead of using a string literal type, you could move thefunction definition after the class definition. This is not alwaysdesirable or even possible, though.

Any type can be entered as a string literal, and you can combinestring-literal types with non-string-literal types freely:

  1. def f(a: List['A']) -> None: ... # OK
  2. def g(n: 'int') -> None: ... # OK, though not useful
  3.  
  4. class A: pass

String literal types are never needed in # type: comments.

String literal types must be defined (or imported) later in the samemodule. They cannot be used to leave cross-module referencesunresolved. (For dealing with import cycles, seeImport cycles.)