Deferred evaluation of annotations and annotationlib
suggest changeBefore Python 3.14, the expressions in type annotations were evaluated as soon as Python ran the def or class statement. That made forward references, such as a class that refers to itself or to a class defined later in the file, fail with NameError unless you put them in quotes.
Python 3.14 evaluates annotations lazily (PEP 649, finalized by PEP 749). The compiler turns the annotations into a small function, and Python only calls it when something asks for the annotations. The new annotationlib module lets code read annotations in three ways: as real values, as values with unresolved names left as ForwardRef objects, or as strings.
This article covers:
- what changed for forward references and when annotations get evaluated
annotationlib.get_annotations()and itsFormat.VALUE,Format.FORWARDREFandFormat.STRINGformats- what
from __future__ import annotationsdoes now - what this means for libraries that read annotations at runtime: dataclasses, pydantic,
functools.singledispatchand metaclasses
Examples were run with Python 3.14.4 (and Python 3.13.15 where noted, to show the old behaviour). The pydantic examples use pydantic 2.14.1. Traceback paths are shortened to the file name.
Type checkers such as mypy and pyright always understood forward references. Lazy evaluation changes what Python does at runtime, not what a type checker reports.
The problem: annotations evaluated too early
Here is a tree whose classes refer to each other:
class Tree:
root: Node | None
def insert(self, value: int) -> Node: ...
class Node:
value: int
left: Node | None
right: Node | None
print(Tree.__annotations__)
print(Tree.insert.__annotations__)
print(Node.__annotations__)
Python 3.13 evaluates Node | None while it executes the body of Tree. At that point Node doesn't exist yet:
$ python3.13 a1.py
Traceback (most recent call last):
File "a1.py", line 1, in <module>
class Tree:
...<2 lines>...
def insert(self, value: int) -> Node: ...
File "a1.py", line 2, in Tree
root: Node | None
^^^^
NameError: name 'Node' is not defined. Did you mean: 'None'?
There were two workarounds:
- write the annotation as a string:
root: "Node | None" - add
from __future__ import annotationsat the top of the module (PEP 563), which stores every annotation as a string and never evaluates it
Both leave you with strings that code reading the annotations has to turn back into objects, usually with typing.get_type_hints().
On Python 3.14 the same file just works, and __annotations__ holds real objects:
$ python3.14 a1.py
{'root': __main__.Node | None}
{'value': <class 'int'>, 'return': <class '__main__.Node'>}
{'value': <class 'int'>, 'left': __main__.Node | None, 'right': __main__.Node | None}
By the time anything reads Tree.__annotations__, Node is defined, so the name resolves. No quotes and no __future__ import are needed.
When annotations are evaluated
Annotations are now evaluated on first access, and the result is cached. A function with side effects in its annotations makes that visible:
def expensive(label):
print(f"evaluating {label}")
return int
def f(x: expensive("x")) -> expensive("return"):
pass
print("function defined")
print(f.__annotations__)
print(f.__annotations__)
Python 3.13 runs the annotation expressions when it executes def:
$ python3.13 b1.py
evaluating x
evaluating return
function defined
{'x': <class 'int'>, 'return': <class 'int'>}
{'x': <class 'int'>, 'return': <class 'int'>}
Python 3.14 runs them only when __annotations__ is first read, and only once:
$ python3.14 b1.py
function defined
evaluating x
evaluating return
{'x': <class 'int'>, 'return': <class 'int'>}
{'x': <class 'int'>, 'return': <class 'int'>}
Besides fixing forward references, this makes importing a module cheaper: most programs never look at annotations at runtime, so the cost of building objects like dict[str, list[int]] for every function is no longer paid at import time.
Gotcha: annotations see the latest binding
Because evaluation happens later, an annotation sees the value a name has when the annotations are read, not when the function was defined:
Alias = int
def f(x: Alias) -> None: ...
Alias = str
print(f.__annotations__)
{'x': <class 'str'>, 'return': None}
On Python 3.13 this prints <class 'int'>. Rebinding a name used in annotations is rare and confusing in any version. Don't do it. If you want a type alias, the type statement from Generics with type parameter syntax (PEP 695) has been lazily evaluated since Python 3.12.
How it works: the __annotate__ function
Functions, classes and modules now have an __annotate__ attribute. It holds a function generated by the compiler that builds the annotations dictionary. It takes a single argument, the format to return the annotations in:
from annotationlib import Format
def area(w: float, h: Undefined) -> float: ...
print(area.__annotate__)
try:
area.__annotate__(Format.VALUE)
except NameError as e:
print("NameError:", e)
try:
area.__annotate__(Format.STRING)
except NotImplementedError:
print("STRING: NotImplementedError")
<function __annotate__ at 0x7ff28aa9f110>
NameError: name 'Undefined' is not defined
STRING: NotImplementedError
Defining area works even though Undefined doesn't exist. The error only shows up when the annotations are evaluated.
The compiler-generated function only supports Format.VALUE. Reading __annotations__ calls __annotate__(Format.VALUE) and caches the result. The other formats are implemented by annotationlib, which calls the same function with a special globals dictionary that records missing names instead of raising. You shouldn't call __annotate__ directly. Use annotationlib.get_annotations().
annotationlib.get_annotations() and formats
annotationlib.get_annotations(obj, format=...) is the recommended way to read annotations of a function, class or module in Python 3.14. (inspect.get_annotations is now the same function.) The format argument decides what you get back:
from annotationlib import Format, get_annotations
def repeat(text: str, times: Count) -> list[str]:
return [text] * times
print(get_annotations(repeat, format=Format.STRING))
print(get_annotations(repeat, format=Format.FORWARDREF))
try:
get_annotations(repeat)
except NameError as e:
print("NameError:", e)
Count = int
print(get_annotations(repeat))
{'text': 'str', 'times': 'Count', 'return': 'list[str]'}
{'text': <class 'str'>, 'times': ForwardRef('Count', owner=<function repeat at 0x7c141306a8d0>), 'return': list[str]}
NameError: name 'Count' is not defined
{'text': <class 'str'>, 'times': <class 'int'>, 'return': list[str]}
The formats are:
| Format | Returns | Undefined names |
|---|---|---|
Format.VALUE (default) |
evaluated objects, like __annotations__ |
raise NameError |
Format.FORWARDREF |
evaluated objects where possible | become annotationlib.ForwardRef objects |
Format.STRING |
each annotation as source-like text | stay as text, nothing is evaluated |
There's also Format.VALUE_WITH_FAKE_GLOBALS, which annotationlib uses internally when it calls an __annotate__ function. You won't pass it yourself.
Pick the format by what your code needs:
VALUEwhen every name must exist, for example in a validation library at the moment it validates dataFORWARDREFwhen you want as much information as possible without failing, for example while a class is being created and the classes it refers to are not defined yetSTRINGfor documentation tools, help text and error messages
STRING format
Format.STRING rebuilds the text of each annotation from the compiled code, without looking up any names:
from annotationlib import Format, get_annotations
def fetch(
url: str,
retry: Policy | None,
on_done: Callable[[Response], Awaitable[None]],
headers: dict[str, "Header"],
) -> tuple[Response, ...]: ...
for name, text in get_annotations(fetch, format=Format.STRING).items():
print(f"{name:8} {text}")
url str
retry Policy | None
on_done Callable[[Response], Awaitable[None]]
headers dict[str, 'Header']
return tuple[Response, ...]
None of Policy, Callable, Response or Awaitable is imported, and it doesn't matter. The text is reconstructed, not copied from the source file, so formatting and comments are not preserved.
ForwardRef objects
A ForwardRef remembers the name it stands for and where it came from (owner). Call evaluate() once the name exists:
from annotationlib import Format, get_annotations
def scale(x: Vector, factor: float) -> Vector: ...
hints = get_annotations(scale, format=Format.FORWARDREF)
ref = hints["x"]
print(type(ref).__name__, ref.__forward_arg__)
try:
ref.evaluate()
except NameError as e:
print("NameError:", e)
class Vector: ...
print(ref.evaluate())
print(ref.evaluate(globals={"Vector": tuple}))
ForwardRef Vector
NameError: name 'Vector' is not defined
<class '__main__.Vector'>
<class 'tuple'>
annotationlib.ForwardRef replaces typing.ForwardRef (the old name is now an alias). evaluate() looks names up in the owner's module by default. Pass globals or locals to resolve them somewhere else. To evaluate a forward ref nested inside a type like list[ForwardRef('X')], use typing.evaluate_forward_ref(), also new in 3.14.
typing.get_type_hints()
typing.get_type_hints() still exists. It also strips Annotated unless you pass include_extras=True, and it resolves string annotations. In 3.14 it accepts a format argument too:
import typing
from annotationlib import Format
class Node:
value: int
next: Node | None
owner: Tree
print(typing.get_type_hints(Node, format=Format.FORWARDREF))
try:
typing.get_type_hints(Node)
except NameError as e:
print("NameError:", e)
{'value': <class 'int'>, 'next': __main__.Node | None, 'owner': ForwardRef('Tree', is_class=True, owner=<class '__main__.Node'>)}
NameError: name 'Tree' is not defined
Imports used only for type checking
A common pattern is to import a module only for the type checker, to avoid import cycles or slow imports. Before 3.14 such names had to be quoted in annotations. Now they don't:
from typing import TYPE_CHECKING
from annotationlib import Format, get_annotations
if TYPE_CHECKING:
from decimal import Decimal
def total(prices: list[Decimal]) -> Decimal:
return sum(prices)
print(get_annotations(total, format=Format.FORWARDREF))
print(get_annotations(total, format=Format.STRING))
try:
get_annotations(total)
except NameError as e:
print("NameError:", e)
{'prices': list[ForwardRef('Decimal', owner=<function total at 0x7c9df62c1640>)], 'return': ForwardRef('Decimal', owner=<function total at 0x7c9df62c1640>)}
{'prices': 'list[Decimal]', 'return': 'Decimal'}
NameError: name 'Decimal' is not defined
The module imports and runs fine. Only code that asks for Format.VALUE (including plain total.__annotations__) fails, because Decimal really isn't defined at runtime. This is a good reason for runtime tools to prefer FORWARDREF.
What happens to from future import annotations
from __future__ import annotations still works in Python 3.14 and keeps its old meaning: every annotation is stored as a string, and there's no __annotate__ function:
from __future__ import annotations
import annotationlib, typing
class User:
name: str
friends: list[User]
print(User.__annotations__)
print(annotationlib.get_annotations(User))
print(annotationlib.get_annotations(User, eval_str=True))
print(typing.get_type_hints(User))
print(User.__annotate__)
{'name': 'str', 'friends': 'list[User]'}
{'name': 'str', 'friends': 'list[User]'}
{'name': <class 'str'>, 'friends': list[__main__.User]}
{'name': <class 'str'>, 'friends': list[__main__.User]}
None
get_annotations(..., eval_str=True) and get_type_hints() evaluate the strings, as before.
What to do with existing code:
- If your code only runs on Python 3.14+, remove the import. Annotations then behave like normal code again, and runtime tools get real objects without having to
eval()strings. - If you support older versions, keep it for now. It's still the only way to use forward references without quotes on 3.13 and earlier.
- PEP 749 plans to deprecate the
__future__import once all Python versions without lazy annotations have reached end of life. It isn't deprecated in 3.14.
None and Optional and Nested classes mention the __future__ import as a workaround. On 3.14 it isn't needed for either.
Impact on libraries that read annotations
Most code never reads annotations at runtime, so for most code lazy evaluation is just "forward references work". Libraries that do read them (dataclasses, pydantic, attrs, FastAPI, functools.singledispatch, dependency-injection frameworks, command-line parsers) are affected in two ways:
- They can now see annotations that refer to names which don't exist yet when the class is created.
- They should read annotations through
annotationlib.get_annotations()rather than__annotations__, so they can choose a format instead of crashing withNameError.
dataclasses
@dataclass only needs the field names and a few special annotations like ClassVar. In 3.14 it reads annotations with Format.FORWARDREF, so a dataclass can refer to classes defined later (see Dataclasses):
import inspect
import typing
from annotationlib import Format
from dataclasses import dataclass, fields
@dataclass
class Order:
id: int
customer: Customer
items: list[Item]
print(Order(1, "alice", []))
for f in fields(Order):
print(f.name, repr(f.type))
print(inspect.signature(Order, annotation_format=Format.STRING))
class Customer: ...
class Item: ...
print(typing.get_type_hints(Order))
print(inspect.signature(Order))
Order(id=1, customer='alice', items=[])
id <class 'int'>
customer ForwardRef('Customer', is_class=True, owner=<class '__main__.Order'>)
items list[ForwardRef('Item', is_class=True, owner=<class '__main__.Order'>)]
(id: 'int', customer: 'Customer', items: 'list[Item]') -> 'None'
{'id': <class 'int'>, 'customer': <class '__main__.Customer'>, 'items': list[__main__.Item]}
(id: int, customer: __main__.Customer, items: list[__main__.Item]) -> None
Field.type holds whatever was available when the class was created, here ForwardRef objects. Call typing.get_type_hints() later to get the resolved types. Also note that a dataclass doesn't check types at runtime: customer='alice' is accepted.
inspect.signature() reads annotations too, and in 3.14 it takes an annotation_format argument. Calling inspect.signature(Order) with the default Format.VALUE before Customer exists raises NameError. Once Customer and Item are defined it works.
pydantic
pydantic validates data against annotations, so it needs real types. It collects annotations as forward references when the class is created and resolves them on first use:
from pydantic import BaseModel
class Order(BaseModel):
id: int
customer: Customer
try:
Order(id=1, customer={"name": "alice"})
except Exception as e:
print(type(e).__name__, e)
class Customer(BaseModel):
name: str
print(Order(id="1", customer={"name": "alice"}))
PydanticUserError `Order` is not fully defined; you should define `Customer`, then call `Order.model_rebuild()`.
For further information visit https://errors.pydantic.dev/2.14/u/class-not-fully-defined
id=1 customer=Customer(name='alice')
Creating the model before Customer exists fails with a clear error. After Customer is defined, the next use rebuilds the model automatically. Calling Order.model_rebuild() explicitly does the same thing up front.
Self-referencing models, which used to need quotes or the __future__ import, now work as written:
from pydantic import BaseModel
class Category(BaseModel):
name: str
parent: Category | None = None
children: list[Category] = []
c = Category(name="books", children=[{"name": "python"}])
print(c)
name='books' parent=None children=[Category(name='python', parent=None, children=[])]
functools.singledispatch
singledispatch.register uses the annotation of the first parameter to pick the type to dispatch on. It needs that type immediately, so it can't wait for a forward reference:
import functools
@functools.singledispatch
def show(x) -> str:
return "something"
@show.register
def _(x: int) -> str:
return f"int {x}"
@show.register
def _(x: Money) -> str:
return f"money {x.cents}"
Traceback (most recent call last):
File "c3.py", line 11, in <module>
@show.register
^^^^^^^^^^^^^
File "/usr/lib/python3.14/functools.py", line 958, in register
raise TypeError(
...<2 lines>...
)
TypeError: Invalid annotation for 'x'. ForwardRef('Money', owner=<function _ at 0x73f401983ab0>) is an unresolved forward reference.
Lazy evaluation doesn't help when a decorator reads annotations at definition time. The class still has to be defined first. The error just got more informative.
Metaclasses and __init_subclass__
Code that inspected the class namespace for "__annotations__" in a metaclass __new__ doesn't find it anymore, because the class body now stores an annotate function instead of a dictionary. Use annotationlib.get_annotate_from_class_namespace() and call_annotate_function():
import annotationlib
from annotationlib import Format
class Meta(type):
def __new__(mcls, name, bases, ns):
print("__annotations__" in ns)
annotate = annotationlib.get_annotate_from_class_namespace(ns)
if annotate:
print(annotationlib.call_annotate_function(annotate, Format.FORWARDREF))
return super().__new__(mcls, name, bases, ns)
class Model(metaclass=Meta):
id: int
owner: User
False
{'id': <class 'int'>, 'owner': ForwardRef('User')}
In __init_subclass__ and class decorators the class already exists, so annotationlib.get_annotations(cls, format=Format.FORWARDREF) is all you need.
Setting annotations yourself
Assigning to __annotations__ still works. It replaces the lazy annotations, and __annotate__ becomes None:
from annotationlib import Format, get_annotations
def f(x: int) -> str: ...
print(f.__annotate__ is not None)
f.__annotations__ = {"x": float, "return": bytes}
print(f.__annotate__)
print(get_annotations(f, format=Format.STRING))
True
None
{'x': 'float', 'return': 'bytes'}
Code that generates functions or classes can also assign its own __annotate__ function. It receives a format and returns a dictionary, or raises NotImplementedError for formats it doesn't support. annotationlib then falls back to another format:
from annotationlib import Format, get_annotations
def make_annotate(fields):
def __annotate__(format):
if format == Format.VALUE:
return dict(fields)
if format == Format.STRING:
return {k: v.__name__ for k, v in fields.items()}
raise NotImplementedError
return __annotate__
def handler(request, user): ...
handler.__annotate__ = make_annotate({"request": dict, "user": str})
print(handler.__annotations__)
print(get_annotations(handler, format=Format.STRING))
print(get_annotations(handler, format=Format.FORWARDREF))
{'request': <class 'dict'>, 'user': <class 'str'>}
{'request': 'dict', 'user': 'str'}
{'request': <class 'dict'>, 'user': <class 'str'>}
FORWARDREF isn't handled by our function, so get_annotations() used VALUE instead.
Supporting older Python versions
annotationlib only exists in 3.14. Libraries that support older versions can use the backport in the typing_extensions package (4.13 or newer), which provides Format and get_annotations() and uses the standard library version on 3.14:
import sys
from typing_extensions import Format, get_annotations
def f(x: "Later", y: "list[int]") -> int: ...
print(sys.version_info[:2])
print(get_annotations(f, format=Format.FORWARDREF))
print(get_annotations(f, format=Format.STRING))
With typing_extensions 4.16.0 on Python 3.13:
(3, 13)
{'x': 'Later', 'y': 'list[int]', 'return': <class 'int'>}
{'x': 'Later', 'y': 'list[int]', 'return': 'int'}
The annotations are quoted here because Python 3.13 still evaluates them eagerly. A string annotation stays a string in FORWARDREF format, on 3.14 too.
Summary
| API | Since | What it does |
|---|---|---|
| lazy annotations | 3.14 | annotations evaluated on first access; forward references work without quotes |
obj.__annotate__ |
3.14 | compiler-generated function that builds the annotations |
annotationlib.get_annotations(obj, format=...) |
3.14 | read annotations as VALUE, FORWARDREF or STRING |
annotationlib.ForwardRef.evaluate() |
3.14 | resolve a forward reference once the name exists |
typing.get_type_hints(obj, format=...) |
3.5 (format in 3.14) |
resolved type hints, Annotated stripped by default |
inspect.signature(obj, annotation_format=...) |
3.3 (annotation_format in 3.14) |
signature with annotations in the chosen format |
from __future__ import annotations |
3.7 | store all annotations as strings (still supported) |
Things to remember:
- On 3.14, write forward references without quotes:
def add(self, other: Vector) -> Vector. - Annotations are evaluated once, on first access, using the names visible at that moment.
- Reading
__annotations__is the same asFormat.VALUEand raisesNameErrorfor undefined names. Tools should useannotationlib.get_annotations()and usuallyFormat.FORWARDREF. from __future__ import annotationsstill turns annotations into strings. Drop it in 3.14-only code.- Decorators that need a type immediately, like
singledispatch.register, still require the class to be defined first. - Other typing features also benefit at runtime:
TypeIsandParamSpecannotations, orTypedDictandProtocolclasses like those in TypedDict, Required, NotRequired and ReadOnly and Protocols, Literal and Final, can refer to classes defined later in the module.