Python 3.7+typingterm
typing.ForwardRef
generics and parameters
The internal representation of a string (forward) annotation; keeps the source in __forward_arg__.
Syntax
typing.ForwardRef('SomeType')
You almost never build one by hand — a ForwardRef appears on its own when a string (say 'Node', referring to a not-yet-defined class) is passed to a typing generic such as Optional['Node'] or List['Node']. A string annotation on a function stays a plain str in __annotations__, and list['Node'] keeps the string too. It is typing.get_type_hints() that later resolves these deferred references back into real types.
Examples
# Python 3.9+
from typing import ForwardRef, Optional, get_type_hints
print(ForwardRef('int').__forward_arg__) # → int
print(type(Optional['Node'].__args__[0]) is ForwardRef) # → True
print(type(list['Node'].__args__[0]) is ForwardRef) # → False
from typing import ForwardRef, Optional, get_type_hints
def f(x: 'int') -> None: pass
print(get_type_hints(f)['x'] is int) # → True
print(isinstance(ForwardRef('int'), type)) # → False
See also
Open in the full glossarydocs.python.orgReport an inaccuracy