Python Glossary Русский

Python 3.14+annotationlibterm

annotationlib.ForwardRef

annotation formats

A placeholder for a name in an annotation that cannot be evaluated yet. It keeps the reference text and can resolve it later with evaluate().

Syntax

ref.evaluate(*, owner=None, globals=None, locals=None, type_params=None, format=Format.VALUE)

A ForwardRef from get_annotations(format=FORWARDREF) remembers its owner, so once the class exists a bare ref.evaluate() is enough. A hand-made ForwardRef('Point') knows no owner: evaluate() looks the name up in empty globals (only builtins are visible) and raises NameError even if Point is defined right there, so pass owner= or globals=. evaluate(format=Format.STRING) just returns __forward_arg__. It is the same class as typing.ForwardRef: typing re-exports it in 3.14.

Examples

# Python 3.14+
from annotationlib import get_annotations, Format
def area(s: Square) -> float: ...
ref = get_annotations(area, format=Format.FORWARDREF)['s']
print(ref.__forward_arg__)  # → Square
class Square: ...
print(ref.evaluate())  # → <class '__main__.Square'> — владелец запомнен
# Python 3.14+
from annotationlib import ForwardRef
class Point: ...
try:
    ForwardRef('Point').evaluate()  # владельца нет — globals пусты
except NameError as e:
    print(e)  # → name 'Point' is not defined
print(ForwardRef('Point').evaluate(globals={'Point': Point}))  # → <class '__main__.Point'>
print(ForwardRef('list[int]').evaluate())  # → list[int] — встроенные видны

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy