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:
- def f(x: A) -> None: # Error: Name A not defined
- ...
- class A:
- ...
In cases like these you can enter the type as a string literal — thisis a forward reference:
- def f(x: 'A') -> None: # OK
- ...
- class A:
- ...
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:
- def f(a: List['A']) -> None: ... # OK
- def g(n: 'int') -> None: ... # OK, though not useful
- 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.)