Python 3.14+annotationlibfunction
annotationlib.get_annotations()
retrieving annotations
The main way to read the annotations of a function, class or module in Python 3.14+, with a choice of format and no crash on forward references.
Syntax
annotationlib.get_annotations(obj, *, globals=None, locals=None, eval_str=False, format=Format.VALUE)
The default format is VALUE: a forward reference to an undefined name raises NameError rather than giving a string, so tools should pass format=Format.FORWARDREF. Every call returns a new dict, so editing the result does not affect the object. Base class annotations are not included, unlike typing.get_type_hints, which collects them along the MRO. eval_str=True is allowed only with VALUE, and an object without annotations (a number, say) raises TypeError. In 3.14 inspect.get_annotations is this same function.
Examples
# Python 3.14+
from annotationlib import get_annotations, Format
class Node:
value: int
next: Node | None # имя самого класса — ссылка вперёд
print(get_annotations(Node, format=Format.STRING)) # → {'value': 'int', 'next': 'Node | None'}
print(get_annotations(Node)['next']) # → __main__.Node | None — класс уже создан
# Python 3.14+
import typing
from annotationlib import get_annotations
class Base:
x: int
class Child(Base):
y: str
print(get_annotations(Child)) # → {'y': <class 'str'>}
print(typing.get_type_hints(Child)) # → {'x': <class 'int'>, 'y': <class 'str'>}
get_annotations(5) # → TypeError: 5 does not have annotations
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy