How to Use Python 3.14 Deferred Annotations: Drop Quoted Forward References, Read Annotations Safely With annotationlib, and Catch the Decorator, Dataclass, and FastAPI Traps
A hands-on Python 3.14 tutorial: watch annotations wait until they are read, use annotationlib, find the decorator, dataclass, Pydantic, and FastAPI traps, and add a tested checker to CI.
Until Python 3.13, Python by default looked up every name in an annotation at the moment it ran the def or class statement that contained it. A function that mentioned a class defined further down the file failed right there, which is why so much Python code wraps type names in quotes. Python 3.14 changed the rule. Its release notes say that annotations “are no longer evaluated eagerly” and that it “is no longer necessary to enclose annotations in strings if they contain forward references.”
Table Of Content
- The ideas you need first, in plain language
- Prerequisites
- Set up one virtual environment per Python version
- Step 1: See the old problem and the new behavior
- What the code does
- Run it on Python 3.13 and then on Python 3.14
- Why 3.14 does not fail
- Step 2: Prove that annotations now wait until you read them
- Step 3: Read annotations safely with annotationlib
- The three formats
- Try all three
- Step 4: Decide what to do about the future import
- Is the import going away?
- Three rules for your own code
- Step 5: Use quote-free forward references in a dataclass, and read the types correctly
- Step 6: Learn which calls evaluate annotations, and fix the decorator trap
- A map of the calls
- The trap: a decorator that reads annotations too early
- A quieter version of the same bug
- Reading annotations from an instance
- Step 7: Check what your frameworks do with the new rules
- Pydantic
- FastAPI
- Step 8: Measure what deferral does to start-up time
- Step 9: Build a checker and put it in CI
- The four findings
- The code
- Try it on a small project
- Test the checker
- Prove the tests can fail
- Common mistakes and how to check for each
- Reading annotations while the module loads
- Treating a dataclass field type as a class
- Assuming a framework resolves forward references the way Python does
- Removing quotes while 3.13 is still supported
- Naming a type only under TYPE_CHECKING
- Writing code against private details
- Confirm the whole thing works end to end
- Where to go next
- Sources and method
That is a real gain for readability, but it also moves the moment of failure. A missing name no longer stops the module from loading. It stops whichever code reads the annotation first, such as a decorator, a framework, a test, or a documentation tool. A few libraries do not stop at all and quietly behave differently, and you will meet one of them in Step 7.
In this tutorial you will run small programs on Python 3.13, 3.14, and 3.15 and read exactly what each one prints. By the end you will be able to remove quoted forward references when it is safe, read annotations without crashing by using the new annotationlib module, tell which standard calls evaluate annotations and which do not, avoid the traps in decorators, dataclasses, Pydantic, and FastAPI, measure what deferral does to start-up time, and put a small checker with tests into your CI so the risky spots in your own code show up before your users find them. Nothing here needs a server or an account, and the whole lab runs in a few minutes.
The ideas you need first, in plain language
An annotation is the part of a function signature or variable that follows a colon or an arrow, as in def f(x: int) -> str or count: int = 0. Python keeps a function’s annotations in a dictionary called __annotations__. A type hint is simply an annotation used to describe a type.
Evaluating an annotation means running the expression to get a value. An annotation is ordinary Python, so evaluating list[Order] looks up the name Order and builds a generic type from it. If the name does not exist yet, Python raises a NameError.
A forward reference is an annotation that names something defined later in the file. The classic case is two classes that mention each other: one of them has to come first, so one of the two annotations points forward. Before 3.14 the workaround was to put the later name in quotes, which turns it into plain text that Python does not evaluate.
The annotationlib documentation describes three models for when evaluation happens, and all three are still in use today:
| Model | Python versions | What __annotations__ holds |
When names are looked up |
|---|---|---|---|
| Stock (eager) | 3.0 to 3.13 | The real objects | When the def or class statement runs |
| Stringified | 3.7 and newer, with from __future__ import annotations |
Plain strings | Only if some code evaluates the strings later |
| Deferred | 3.14 and newer, the default | The real objects, built on first read | The first time something reads the annotations |
For the third model the documentation says: “Annotations are evaluated lazily, only when they are accessed.” Everything in the rest of this tutorial follows from that one sentence.
Prerequisites
You need a terminal, Python 3.14 or newer for most steps, and Python 3.13 for the comparison runs in Steps 1, 2, 5, 6, 7, and 8. Python 3.15 appears in a few outputs so you can see that it behaves like 3.14. You should be comfortable writing functions and classes and running a script, but you do not need any typing experience. Steps 7 and 9 use pydantic, fastapi, httpx, and pytest.
Every result below came from Windows 11 with CPython 3.13.14, 3.14.10, and 3.15.2, Pydantic 2.14.4, FastAPI 0.165.0, Starlette 1.10.0, httpx 0.28.1, and pytest 9.2.0. Your timings will differ, and library behavior can change with a new release, so treat the framework steps as a method you can repeat rather than as a promise.
Set up one virtual environment per Python version
A virtual environment keeps one Python version and its packages in a folder, so you can run the same file under several versions without mixing them up. On macOS or Linux:
python3.14 -m venv venv314
venv314/bin/python -m pip install pydantic fastapi httpx pytest
python3.13 -m venv venv313
venv313/bin/python -m pip install pydantic fastapi httpx pytest
venv314/bin/python --version
On Windows, write py -3.14 -m venv venv314 and use venv314\Scripts\python.exe in place of venv314/bin/python. If Python 3.14 is not installed yet, uv python install 3.14 installs it. The last command should print a version that starts with Python 3.14. Make a folder called annolab and put every file from this tutorial in it: the first line of each code block is a comment that names the file.
Step 1: See the old problem and the new behavior
What the code does
We start with the situation that made people quote their annotations: two classes that each mention the other.
# step01_forward.py
import sys
print("Python", sys.version.split()[0])
class Order:
def customer(self) -> Customer:
raise NotImplementedError
class Customer:
def orders(self) -> list[Order]:
raise NotImplementedError
print(Order.customer.__annotations__)
print(Customer.orders.__annotations__)
Order has a method whose return annotation is Customer, and Customer has a method whose return annotation is list[Order]. When Python runs def customer, the name Customer does not exist yet, because that class is defined a few lines further down. The last two lines print each method’s annotations dictionary.
Run it on Python 3.13 and then on Python 3.14
venv313/bin/python step01_forward.py
venv314/bin/python step01_forward.py
On Python 3.13.14 the program stops at the first def:
Python 3.13.14
NameError: name 'Customer' is not defined
This is the old behavior. Python evaluated the annotation on the spot and found no Customer. The annotationlib documentation describes this exact case: “Under stock semantics (Python 3.13 and earlier), it will throw a NameError at the line where func is defined, because Cls is an undefined name at that point.”
On Python 3.14.10 the same file runs:
Python 3.14.10
{'return': <class '__main__.Customer'>}
{'return': list[__main__.Order]}
Why 3.14 does not fail
Nothing looked up Customer while Order was being defined. By the time the last two lines read the annotations, both classes existed. The names in the output, such as __main__.Customer, are how Python prints a class: the module name, a dot, then the class name. Python 3.15.2 printed the same two dictionaries. Before you move on, check that your 3.13 run ends with a NameError and your 3.14 run prints two dictionaries; if both versions behave the same, you are running the wrong interpreter.
Step 2: Prove that annotations now wait until you read them
Step 1 showed that 3.14 does not fail, but not why. This script makes the laziness visible. An annotation can be any expression, including a function call, so we annotate a function with calls to probe, which records its argument in a list and returns int. The list becomes a log of exactly when annotations run.
# step02_lazy.py
import sys
calls = []
def probe(name):
calls.append(name)
return int
def add(a: probe("a"), b: probe("b")) -> probe("return"):
return a + b
print("Python", sys.version.split()[0])
print("after def :", calls)
print("annotations :", add.__annotations__)
print("after first read :", calls)
add.__annotations__
print("after second read :", calls)
if sys.version_info >= (3, 14):
print("has __annotate__ :", callable(add.__annotate__))
On Python 3.13.14 the log fills up while the def statement runs:
Python 3.13.14
after def : ['a', 'b', 'return']
annotations : {'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}
after first read : ['a', 'b', 'return']
after second read : ['a', 'b', 'return']
On Python 3.14.10 the log is empty after the def:
Python 3.14.10
after def : []
annotations : {'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}
after first read : ['a', 'b', 'return']
after second read : ['a', 'b', 'return']
has __annotate__ : True
Read the four lines in order. After the def statement the list is empty, so nothing has been evaluated. The first read of add.__annotations__ runs the three probe calls and returns the dictionary. The second read adds nothing, because Python keeps the dictionary after building it once. The last line shows that the function now carries a callable __annotate__. That small function is how the deferral works: in the release notes’ words, “annotations are stored in special-purpose annotate functions and evaluated only when necessary.” Python 3.15.2 printed the same lines as 3.14.10.
Step 3: Read annotations safely with annotationlib
The three formats
The new standard-library module annotationlib has one main function, get_annotations(), that returns annotations in a format you choose. The how-to guide says it “supersedes inspect.get_annotations()”, so it is the one to learn. The formats answer one question: what should Python do when an annotation names something that does not exist yet?
| Format | A missing name gives | Good for |
|---|---|---|
VALUE |
A NameError |
Code that needs real classes and can wait until everything is defined |
FORWARDREF |
A ForwardRef placeholder in place of the name |
Code that runs while a module is still loading, such as decorators and registries |
STRING |
The annotation as source text | Documentation, logging, and error messages |
The documentation puts it this way: VALUE “may raise errors, for example if the annotations contain references to undefined names”; FORWARDREF “returns ForwardRef objects for annotations that cannot be resolved”; and STRING “returns the annotations as a string, similar to how it would appear in the source file.”
Try all three
The function handler below mentions Order and Receipt, which are defined only after it. The loops ask for all three formats before the classes exist and again after. The helper show only tidies the output: it removes the owner= part that a ForwardRef normally prints, because that part holds a memory address that changes on every run.
# step03_formats.py
import re
from annotationlib import Format, get_annotations
def handler(order: Order, retries: int = 3) -> list[Receipt]:
return []
def show(value):
if isinstance(value, str):
return value
return re.sub(r", owner=<[^>]*>", "", repr(value))
def dump(label, fmt):
print(label)
try:
annotations = get_annotations(handler, format=fmt)
except NameError as exc:
print(" NameError:", exc)
return
for key, value in annotations.items():
print(f" {key:<8}{show(value)}")
for fmt in (Format.VALUE, Format.FORWARDREF, Format.STRING):
dump(f"{fmt.name}, before Order and Receipt exist", fmt)
class Order:
pass
class Receipt:
pass
for fmt in (Format.VALUE, Format.FORWARDREF, Format.STRING):
dump(f"{fmt.name}, after they exist", fmt)
venv314/bin/python step03_formats.py
VALUE, before Order and Receipt exist
NameError: name 'Order' is not defined
FORWARDREF, before Order and Receipt exist
order ForwardRef('Order')
retries <class 'int'>
return list[ForwardRef('Receipt')]
STRING, before Order and Receipt exist
order Order
retries int
return list[Receipt]
VALUE, after they exist
order <class '__main__.Order'>
retries <class 'int'>
return list[__main__.Receipt]
FORWARDREF, after they exist
order <class '__main__.Order'>
retries <class 'int'>
return list[__main__.Receipt]
STRING, after they exist
order Order
retries int
return list[Receipt]
Look at the first three groups, the ones printed before the classes exist. VALUE raises NameError. FORWARDREF returns an answer for every parameter: order is a ForwardRef holding the name, retries is the real class int because there was nothing to wait for, and the return annotation became list[ForwardRef('Receipt')], so the missing name was replaced inside the larger expression. STRING returns source text. In the last three groups, after the classes exist, VALUE and FORWARDREF return the same real objects. Python 3.15.2 printed the same 22 lines.
Step 4: Decide what to do about the future import
You have probably seen from __future__ import annotations at the top of modules. It is the older fix for forward references: it makes Python store every annotation as a string. The next file is the documentation’s own example, plus a call to typing.get_type_hints, which is the standard way to turn those strings back into classes.
# step04_future.py
from __future__ import annotations
import typing
from annotationlib import Format, get_annotations
def func(a: Cls) -> None:
print(a)
class Cls:
pass
print("__annotations__ :", func.__annotations__)
print("VALUE :", get_annotations(func, format=Format.VALUE))
print("get_type_hints :", typing.get_type_hints(func))
__annotations__ : {'a': 'Cls', 'return': 'None'}
VALUE : {'a': 'Cls', 'return': 'None'}
get_type_hints : {'a': <class '__main__.Cls'>, 'return': <class 'NoneType'>}
The first two lines print strings, {'a': 'Cls', 'return': 'None'}, which is exactly what the documentation says this program prints. Even get_annotations with the default VALUE format returns strings here, because the future import tells Python to keep them as text. Calling get_type_hints is what evaluates them and returns the class. In other words, a module that keeps the future import keeps the old stringified behavior on 3.14.
Is the import going away?
The migration notes call the statement deprecated and say that “This removal will not happen until after Python 3.13 reaches its end of life in 2029.” PEP 749, which specifies the plan, adds that compiling code with the import will start to emit a DeprecationWarning “no sooner than the first release after Python 3.13 reaches its end-of-life.” We can check today’s behavior by turning warnings into errors:
venv314/bin/python -W error::DeprecationWarning -c "from __future__ import annotations; print('no warning')"
no warning
That output came from Python 3.14.10; Python 3.13.14 and 3.15.2 printed the same line. Nothing warns in any of the three versions I ran.
Three rules for your own code
First, if you still support Python 3.13 or older, keep the quotes or the future import. Without them, your module fails at import time on those versions, as Step 1 showed. Second, if 3.14 is your minimum, the migration notes say that you “may well be able to remove that import”, so try it one module at a time and run your tests after each change. Third, do not assume a module behaves the same on both sides of the switch. A module that keeps the import still hands out strings, and code that expects real classes will notice, as Step 6 shows.
Step 5: Use quote-free forward references in a dataclass, and read the types correctly
Dataclasses are a common place to meet forward references, because a self-referencing field such as a tree node’s parent needs the class name before the class exists. This script defines a small tree node and leaves the class name unquoted inside its own definition.
# step05_dataclass.py
import re
import typing
from dataclasses import dataclass, field, fields
@dataclass
class Node:
name: str
parent: Node | None = None
children: list[Node] = field(default_factory=list)
def show(value):
return re.sub(r", owner=<[^>]*>", "", repr(value))
root = Node("root")
leaf = Node("leaf", parent=root)
root.children.append(leaf)
print("fields() types:")
for f in fields(Node):
print(f" {f.name:<9}{show(f.type)}")
print("get_type_hints:")
for name, hint in typing.get_type_hints(Node).items():
print(f" {name:<9}{show(hint)}")
print(leaf)
Python 3.13.14 refuses the class statement itself:
NameError: name 'Node' is not defined. Did you mean: 'None'?
The class body evaluates Node | None while Node is still being built, so there is no Node yet. Python 3.14.10 accepts it:
fields() types:
name <class 'str'>
parent ForwardRef('Node | None', is_class=True)
children list[ForwardRef('Node', is_class=True)]
get_type_hints:
name <class 'str'>
parent __main__.Node | None
children list[__main__.Node]
Node(name='leaf', parent=Node(name='root', parent=None, children=[...]), children=[])
Two details deserve a slow read. First, the class works: leaf points at root and the last line prints normally. Second, look at what fields() reports. For parent it shows ForwardRef('Node | None', is_class=True), and for children it shows list[ForwardRef('Node', is_class=True)]. The @dataclass decorator runs before the name Node is bound, so it cannot resolve the self-reference and keeps a placeholder. That matches the migration advice to use get_annotations() “with the FORWARDREF format, as the dataclasses module now does.” The placeholder does not turn into the class later, even though the output was printed after Node existed. If you need the real types, ask for them at a time when they exist: typing.get_type_hints(Node), shown in the last block, returns Node | None and list[Node]. Python 3.15.2 printed the same lines as 3.14.10.
Step 6: Learn which calls evaluate annotations, and fix the decorator trap
A map of the calls
Reading annotations is not one operation. Some calls evaluate them and fail on a missing name, and others hand back placeholders. This script defines a function whose annotations name classes that never exist, then tries eleven calls on it and prints ok or NameError for each.
# step06_who_evaluates.py
import functools
import inspect
import typing
from annotationlib import Format, get_annotations
def ship(order: Order) -> Receipt:
return None
OPERATIONS = {
"ship.__annotations__": lambda: ship.__annotations__,
"inspect.signature(ship)": lambda: inspect.signature(ship),
"inspect.signature(ship, annotation_format=Format.FORWARDREF)": lambda: inspect.signature(
ship, annotation_format=Format.FORWARDREF
),
"typing.get_type_hints(ship)": lambda: typing.get_type_hints(ship),
"typing.get_type_hints(ship, format=Format.FORWARDREF)": lambda: typing.get_type_hints(
ship, format=Format.FORWARDREF
),
"get_annotations(ship)": lambda: get_annotations(ship),
"get_annotations(ship, format=Format.FORWARDREF)": lambda: get_annotations(
ship, format=Format.FORWARDREF
),
"get_annotations(ship, format=Format.STRING)": lambda: get_annotations(
ship, format=Format.STRING
),
"functools.wraps(ship)": lambda: functools.wraps(ship)(lambda: 0),
"repr(ship)": lambda: repr(ship),
"ship.__annotate__": lambda: ship.__annotate__,
}
for label, operation in OPERATIONS.items():
try:
operation()
verdict = "ok"
except NameError:
verdict = "NameError"
print(f"{verdict:<10}{label}")
NameError ship.__annotations__
NameError inspect.signature(ship)
ok inspect.signature(ship, annotation_format=Format.FORWARDREF)
NameError typing.get_type_hints(ship)
ok typing.get_type_hints(ship, format=Format.FORWARDREF)
NameError get_annotations(ship)
ok get_annotations(ship, format=Format.FORWARDREF)
ok get_annotations(ship, format=Format.STRING)
ok functools.wraps(ship)
ok repr(ship)
ok ship.__annotate__
Four calls raise: reading ship.__annotations__, inspect.signature(ship), typing.get_type_hints(ship), and get_annotations(ship) with its default format. Each one asks for real objects. The other seven succeed because they either ask for a placeholder (annotation_format=Format.FORWARDREF, format=Format.FORWARDREF, and Format.STRING) or never look at the annotations at all: functools.wraps, repr, and reading __annotate__. Python 3.15.2 printed the same eleven lines. The practical lesson is that inspect.signature evaluates by default. Frameworks such as FastAPI call it while a route is being registered (Step 7), and home-made decorators often do too.
The trap: a decorator that reads annotations too early
Here is the pattern that breaks. checked_eager reads func.__annotations__ immediately, while the decorator is being applied, and uses the dictionary later to compare arguments with their annotated classes. checked_lazy does the same job but reads the annotations on the first call.
# step06b_decorator_trap.py
import functools
from annotationlib import get_annotations
def _check(func, hints, args):
for name, value in zip(func.__code__.co_varnames, args):
expected = hints.get(name)
if isinstance(expected, type) and not isinstance(value, expected):
raise TypeError(f"{name} must be {expected.__name__}, not {type(value).__name__}")
def checked_eager(func):
hints = func.__annotations__ # evaluated while the decorator runs
@functools.wraps(func)
def wrapper(*args):
_check(func, hints, args)
return func(*args)
return wrapper
def checked_lazy(func):
cache = {}
@functools.wraps(func)
def wrapper(*args):
if not cache:
cache.update(get_annotations(func)) # evaluated on the first call
_check(func, cache, args)
return func(*args)
return wrapper
try:
@checked_eager
def ship_eager(order: Order) -> Receipt:
return Receipt()
except NameError as exc:
print("eager decorator:", type(exc).__name__, "-", exc)
@checked_lazy
def ship_lazy(order: Order) -> Receipt:
return Receipt()
class Order:
pass
class Receipt:
pass
print("lazy decorator, good call:", type(ship_lazy(Order())).__name__)
try:
ship_lazy("not an order")
except TypeError as exc:
print("lazy decorator, bad call :", exc)
eager decorator: NameError - name 'Order' is not defined
lazy decorator, good call: Receipt
lazy decorator, bad call : order must be Order, not str
The first line is the trap. Applying checked_eager to ship_eager raised NameError, because Order is defined further down the file. The lazy version survived decoration; by the first call both classes existed, so the check worked: a good call passed, and a bad call raised TypeError: order must be Order, not str.
The fix follows one rule: do not evaluate annotations while a module is still loading. Either wait for the first call, as checked_lazy does, or ask for placeholders at decoration time with Format.FORWARDREF and resolve them later.
A quieter version of the same bug
The future import hides this problem in a worse way. In the next file the same eager decorator is applied to a module that uses the import.
# step06d_future_noop.py
from __future__ import annotations
import functools
def checked_eager(func):
hints = func.__annotations__
@functools.wraps(func)
def wrapper(*args):
for name, value in zip(func.__code__.co_varnames, args):
expected = hints.get(name)
if isinstance(expected, type) and not isinstance(value, expected):
raise TypeError(f"{name} must be {expected.__name__}")
return func(*args)
return wrapper
@checked_eager
def ship(order: Order) -> None:
pass
class Order:
pass
print("annotation stored:", repr(ship.__wrapped__.__annotations__["order"]))
ship("not an order")
print("no error: the check was silently skipped")
annotation stored: 'Order'
no error: the check was silently skipped
Python 3.13.14 printed the same two lines. The decorator reads the stored annotation without any error, but the value is the string 'Order', which is not a class, so isinstance(expected, type) is false and the check is skipped. The call with a wrong argument went through. If a module uses the future import together with a decorator like this one, the decorator has been checking nothing there, and moving to real annotations would start enforcing it. Test before you remove the import.
Reading annotations from an instance
One more habit to check is reading annotations from an object instead of its class. The release notes say: “In previous releases, it was sometimes possible to access class annotations from an instance of an annotated class. This behavior was undocumented and accidental, and will no longer work in Python 3.14.” The script below shows the change; its first lines pick annotationlib.get_annotations on 3.14 and fall back to inspect.get_annotations on older versions.
# step06c_instance.py
import sys
if sys.version_info >= (3, 14):
from annotationlib import get_annotations
else:
from inspect import get_annotations
class Point:
x: int
y: int
point = Point()
print("Python", sys.version.split()[0])
print("class :", Point.__annotations__)
try:
print("instance :", point.__annotations__)
except AttributeError as exc:
print("instance : AttributeError:", exc)
print("get_annotations(type(p)):", get_annotations(type(point)))
On Python 3.13.14:
Python 3.13.14
class : {'x': <class 'int'>, 'y': <class 'int'>}
instance : {'x': <class 'int'>, 'y': <class 'int'>}
get_annotations(type(p)): {'x': <class 'int'>, 'y': <class 'int'>}
On Python 3.14.10:
Python 3.14.10
class : {'x': <class 'int'>, 'y': <class 'int'>}
instance : AttributeError: 'Point' object has no attribute '__annotations__'
get_annotations(type(p)): {'x': <class 'int'>, 'y': <class 'int'>}
On 3.13 the instance quietly returned its class’s annotations. On 3.14 it raises AttributeError. Read annotations from the class, for example with get_annotations(type(obj)).
Step 7: Check what your frameworks do with the new rules
The migration notes include a warning that applies here: “if you rely on third-party libraries that read annotations, those libraries may need changes to support unquoted annotations before they work as expected.” So the useful question is not whether Python accepts your code but whether the libraries you use understand it. Two quick experiments, run with the versions listed in the prerequisites, show the range of answers.
Pydantic
Two models that refer to each other are a common source of forward references. Team mentions Member before Member exists, and the script reports whether Pydantic considers Team complete.
# step07_pydantic.py
import sys
from pydantic import BaseModel, ValidationError
from pydantic import __version__ as pydantic_version
class Team(BaseModel):
lead: Member
size: int = 1
class Member(BaseModel):
name: str
print("pydantic", pydantic_version, "on Python", sys.version.split()[0])
print("Team complete before first use:", Team.__pydantic_complete__)
team = Team(lead={"name": "Ada"})
print("Team complete after first use :", Team.__pydantic_complete__)
print(team)
try:
Team(lead={"name": 7})
except ValidationError as exc:
error = exc.errors()[0]
print(error["type"], error["loc"])
On Python 3.13.14:
NameError: name 'Member' is not defined
On Python 3.14.10:
pydantic 2.14.4 on Python 3.14.10
Team complete before first use: False
Team complete after first use : True
lead=Member(name='Ada') size=1
string_type ('lead', 'name')
Python 3.13 stops at the class statement. On 3.14 the model class is created even though Member does not exist yet. Pydantic marks Team as incomplete (False), finishes the job on first use once Member exists (True), and validates correctly: the last line is the error from the deliberately wrong value 7 for name, a string_type error at location ('lead', 'name'). In this experiment, quote-free forward references between two models worked on Python 3.14 with Pydantic 2.14.4.
FastAPI
FastAPI is the more interesting case because it reads annotations at the moment you register a route. We use one tiny app in four layouts. In shop_late.py the models come first, which is a common layout. In shop_early.py the route comes first and names models defined below it. The other two files use the same early layout with quotes and with the future import.
# shop_late.py
from fastapi import FastAPI
from pydantic import BaseModel
class Order(BaseModel):
qty: int
class Receipt(BaseModel):
order_id: int
total: int
app = FastAPI()
@app.post("/orders")
def create(order: Order) -> Receipt:
return Receipt(order_id=1, total=order.qty * 2)
# shop_early.py
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
@app.post("/orders")
def create(order: Order) -> Receipt:
return Receipt(order_id=1, total=order.qty * 2)
class Order(BaseModel):
qty: int
class Receipt(BaseModel):
order_id: int
total: int
# shop_early_quoted.py
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
@app.post("/orders")
def create(order: "Order") -> "Receipt":
return Receipt(order_id=1, total=order.qty * 2)
class Order(BaseModel):
qty: int
class Receipt(BaseModel):
order_id: int
total: int
# shop_early_future.py
from __future__ import annotations
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
@app.post("/orders")
def create(order: Order) -> Receipt:
return Receipt(order_id=1, total=order.qty * 2)
class Order(BaseModel):
qty: int
class Receipt(BaseModel):
order_id: int
total: int
The driver imports each module, posts a valid JSON body to /orders, and asks the app for its OpenAPI document. It reports any exception by name instead of crashing, so one broken layout does not hide the next.
# step08_fastapi.py
import importlib
import sys
import fastapi
from fastapi.testclient import TestClient
def failure(exc):
code = getattr(exc, "code", "")
return f"{type(exc).__name__} ({code})" if code else f"{type(exc).__name__}: {exc}"
def describe(module):
client = TestClient(module.app)
try:
response = client.post("/orders", json={"qty": 4})
status = str(response.status_code)
if response.status_code == 422:
status += f" {response.json()['detail'][0]['loc']}"
except Exception as exc:
status = failure(exc)
try:
operation = client.get("/openapi.json").json()["paths"]["/orders"]["post"]
except Exception as exc:
return f"request -> {status}; openapi.json -> {failure(exc)}"
query = [p["name"] for p in operation.get("parameters", []) if p["in"] == "query"]
return f"request -> {status}; query parameters {query}; request body {'requestBody' in operation}"
print("FastAPI", fastapi.__version__, "on Python", sys.version.split()[0])
for name in ("shop_late", "shop_early", "shop_early_quoted", "shop_early_future"):
try:
module = importlib.import_module(name)
except Exception as exc:
print(f"{name:<19}import failed with {failure(exc)}")
continue
print(f"{name:<19}{describe(module)}")
On Python 3.13.14:
FastAPI 0.165.0 on Python 3.13.14
shop_late request -> 200; query parameters []; request body True
shop_early import failed with NameError: name 'Order' is not defined
shop_early_quoted request -> 422 ['query', 'order']; openapi.json -> PydanticUserError (class-not-fully-defined)
shop_early_future request -> 422 ['query', 'order']; openapi.json -> PydanticUserError (class-not-fully-defined)
On Python 3.14.10:
FastAPI 0.165.0 on Python 3.14.10
shop_late request -> 200; query parameters []; request body True
shop_early request -> 422 ['query', 'order']; openapi.json -> PydanticUserError (class-not-fully-defined)
shop_early_quoted request -> 422 ['query', 'order']; openapi.json -> PydanticUserError (class-not-fully-defined)
shop_early_future request -> 422 ['query', 'order']; openapi.json -> PydanticUserError (class-not-fully-defined)
Read the Python 3.14 block first. Only the models-first file works. The other three import without any error and then fail in two ways: a POST with a correct JSON body returns 422 saying a field called order is required in the query string (['query', 'order']), and generating /openapi.json fails with Pydantic’s class-not-fully-defined error. In plain words, FastAPI did not recognize Order as a request body model, because the name did not exist yet when the route was registered, so it expected order in the URL like an ordinary query parameter.
Now compare Python 3.13. The plain early layout fails loudly there, with a NameError at import. The quoted and future-import layouts fail the same quiet way as the plain layout on 3.14. So removing the quotes on 3.14 did not make early routes work; it only moved the plain layout from a loud failure to a quiet one.
The reason is visible in FastAPI’s own source. This is the helper from FastAPI 0.165.0 that reads a function’s signature:
# fastapi/dependencies/utils.py (FastAPI 0.165.0)
def _get_signature(call: Callable[..., Any]) -> inspect.Signature:
try:
signature = inspect.signature(call, eval_str=True)
except NameError:
# Handle type annotations with if TYPE_CHECKING, not used by FastAPI
# e.g. dependency return types
if sys.version_info >= (3, 14):
from annotationlib import Format
signature = inspect.signature(call, annotation_format=Format.FORWARDREF)
else:
signature = inspect.signature(call)
return signature
FastAPI first asks for real values with eval_str=True. If that raises NameError, then on Python 3.14 and newer it falls back to Format.FORWARDREF, so a missing name no longer crashes the import. Its comment says the fallback exists for annotations that depend on TYPE_CHECKING imports, such as the return types of dependencies. What the fallback cannot do is invent the model you have not defined yet, so the parameter stays an unresolved placeholder.
The practical rule: with FastAPI 0.165.0, define request and response models above the routes that use them, on every Python version. And when you upgrade Python, send a request through each route in a test instead of only importing the module, because the 3.14 failure shows up as a 422 at request time, not as an error at start-up.
Step 8: Measure what deferral does to start-up time
One goal of the change was speed: the release notes say that “The runtime cost for defining annotations is minimized.” We can measure that with a generated module of 2,000 functions. Each has the same annotated signature: a union with a nested generic, a Callable, a keyword-only set of frozensets with a default, and a return annotation. The child script builds the source, compiles it, then times two things: running the module (all the def statements) and reading every function’s __annotations__ once.
# bench_child.py
import sys
import time
COUNT = 2000
HEADER = "from __future__ import annotations\n" if sys.argv[1] == "future" else ""
FUNCTION = (
"def f{i}(a: dict[str, list[tuple[int, ...]]] | None, b: Callable[[int], str], *,\n"
" c: set[frozenset[int]] = None) -> list[dict[str, int]]:\n"
" pass\n"
)
source = HEADER + "from collections.abc import Callable\n"
source += "".join(FUNCTION.format(i=i) for i in range(COUNT))
code = compile(source, "generated.py", "exec")
namespace = {"__name__": "generated"}
start = time.perf_counter()
exec(code, namespace)
define = time.perf_counter() - start
start = time.perf_counter()
for i in range(COUNT):
namespace[f"f{i}"].__annotations__
read = time.perf_counter() - start
print(f"{define * 1000:.2f} {read * 1000:.2f}")
The parent script starts the child in a fresh process 15 times for each case and prints the median, because timings inside one long-running process drift as caches warm up. Pass it the interpreters you want to compare:
# bench.py
import statistics
import subprocess
import sys
RUNS = 15
LABELS = {"plain": "no future import", "future": "future import"}
# usage: python bench.py 3.13=venv313/bin/python 3.14=venv314/bin/python
interpreters = dict(arg.split("=", 1) for arg in sys.argv[1:])
print(f"2,000 annotated functions, median of {RUNS} fresh processes, milliseconds")
print(f"{'Python':<8}{'mode':<20}{'define':>8}{'first read':>12}")
for version, python in interpreters.items():
for mode in ("plain", "future"):
define, read = [], []
for _ in range(RUNS):
done = subprocess.run(
[python, "bench_child.py", mode], capture_output=True, text=True, check=True
)
first, second = done.stdout.split()
define.append(float(first))
read.append(float(second))
print(
f"{version:<8}{LABELS[mode]:<20}{statistics.median(define):>8.1f}"
f"{statistics.median(read):>12.1f}"
)
venv314/bin/python bench.py 3.13=venv313/bin/python 3.14=venv314/bin/python
The run I used also included Python 3.15.2:
2,000 annotated functions, median of 15 fresh processes, milliseconds
Python mode define first read
3.13 no future import 6.1 0.3
3.13 future import 3.0 0.3
3.14 no future import 3.0 4.5
3.14 future import 3.2 0.4
3.15 no future import 2.8 4.0
3.15 future import 3.0 0.3
Read the table by comparing rows within one Python version. On 3.13, running the 2,000 def statements took 6.1 ms, and 3.0 ms when the future import turned the annotations into strings, so evaluating them cost about 3 ms. On 3.14 without the import, defining took 3.0 ms, close to the 3.2 ms of the stringified version, because nothing was evaluated yet. The cost did not disappear: the first read of all 2,000 annotation dictionaries took 4.5 ms. Python 3.15.2 shows the same pattern with 2.8 ms to define and 4.0 ms for the first read.
The honest summary is that deferral moves work to the moment someone reads. If your program never reads annotations, it saves roughly 3 ms per 2,000 annotated functions at start-up. If a framework reads all of them, the total here was 7.5 ms on 3.14 against 6.4 ms on 3.13, about a millisecond more. These are small numbers from a synthetic module on one machine, so take them as a direction rather than a prediction. The saving should grow with the number of annotated functions, so measure your own import time before you quote a figure.
Step 9: Build a checker and put it in CI
You now know the failure modes. This step turns them into a tool you can run on your own code. The tool, annocheck.py, has two parts. A static part reads source files with the ast module and reports code that is affected by the change. A runtime part imports your modules and asks typing.get_type_hints to resolve every annotation, which is close to what frameworks do when they need the real types.
The four findings
| Code | Meaning | What to do |
|---|---|---|
ANN1 |
The module uses from __future__ import annotations |
Keep it while you support 3.13; consider removing it later |
ANN2 |
A quoted annotation that can lose its quotes on 3.14 and newer | Unquote it only when 3.14 is your minimum version |
ANN3 |
Code that evaluates annotations: __annotations__, get_type_hints(), or signature() |
Review it with Step 6 in mind |
ANN4 |
A name that typing.get_type_hints cannot resolve |
Fix it: this is a real error and makes the exit code 1 |
The code
Read it from the top. _quoted walks an annotation and yields only the strings that are forward references. It skips everything inside Literal[...], because those strings are values, and it looks only at the first item of Annotated[...], because the rest is metadata. _annotations collects every annotation in a file: parameters of all kinds, return annotations, and annotated variables. scan_source produces the first three finding types, and unresolved produces the fourth.
# annocheck.py
"""annocheck.py: report annotation problems that matter on Python 3.14 and newer."""
import argparse
import ast
import importlib
import inspect
import sys
import typing
from dataclasses import dataclass
from pathlib import Path
@dataclass(frozen=True)
class Finding:
code: str
path: str
line: int
message: str
def __str__(self):
where = f"{self.path}:{self.line}" if self.line else self.path
return f"{where}: {self.code} {self.message}"
def _base_name(node):
if isinstance(node, ast.Name):
return node.id
if isinstance(node, ast.Attribute):
return node.attr
return None
def _quoted(expr):
"""Yield the string constants in an annotation that are forward references."""
if isinstance(expr, ast.Constant):
if isinstance(expr.value, str):
yield expr
elif isinstance(expr, ast.Subscript):
base = _base_name(expr.value)
if base == "Literal":
return
items = expr.slice.elts if isinstance(expr.slice, ast.Tuple) else [expr.slice]
if base == "Annotated":
items = items[:1]
for item in items:
yield from _quoted(item)
elif isinstance(expr, ast.BinOp):
yield from _quoted(expr.left)
yield from _quoted(expr.right)
elif isinstance(expr, (ast.Tuple, ast.List)):
for item in expr.elts:
yield from _quoted(item)
def _annotations(tree):
for node in ast.walk(tree):
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
a = node.args
params = a.posonlyargs + a.args + a.kwonlyargs + [x for x in (a.vararg, a.kwarg) if x]
for param in params:
if param.annotation is not None:
yield param.annotation
if node.returns is not None:
yield node.returns
elif isinstance(node, ast.AnnAssign):
yield node.annotation
def scan_source(source, path="<string>"):
"""Static findings: ANN1 future import, ANN2 quoted annotation, ANN3 code that evaluates annotations."""
tree = ast.parse(source)
found = []
for node in ast.walk(tree):
if isinstance(node, ast.ImportFrom) and node.module == "__future__":
if any(alias.name == "annotations" for alias in node.names):
found.append(Finding("ANN1", path, node.lineno, "the future import turns every annotation into a string"))
elif isinstance(node, ast.Attribute) and node.attr == "__annotations__":
found.append(Finding("ANN3", path, node.lineno, "reads __annotations__, which evaluates deferred annotations"))
elif isinstance(node, ast.Call) and _base_name(node.func) in ("get_type_hints", "signature"):
found.append(Finding("ANN3", path, node.lineno, f"calls {_base_name(node.func)}(), which evaluates annotations"))
for expr in _annotations(tree):
for const in _quoted(expr):
found.append(Finding("ANN2", path, const.lineno, f"quoted annotation {const.value!r} can lose its quotes on Python 3.14+"))
return sorted(found, key=lambda f: (f.line, f.code))
def unresolved(module):
"""ANN4: names that typing.get_type_hints cannot resolve for what a module defines."""
problems = []
for name, obj in sorted(vars(module).items()):
if not (inspect.isfunction(obj) or inspect.isclass(obj)):
continue
if getattr(obj, "__module__", None) != module.__name__:
continue
targets = [(name, obj)]
if inspect.isclass(obj):
targets += [(f"{name}.{m}", f) for m, f in vars(obj).items() if inspect.isfunction(f)]
for label, target in targets:
try:
typing.get_type_hints(target)
except NameError as exc:
problems.append(Finding("ANN4", module.__name__, 0, f"{label}: {exc}"))
return problems
def main(argv=None):
parser = argparse.ArgumentParser(prog="annocheck")
parser.add_argument("paths", nargs="*", type=Path)
parser.add_argument("--import", dest="modules", action="append", default=[], metavar="MODULE")
parser.add_argument("--strict", action="store_true", help="exit 1 on any finding")
args = parser.parse_args(argv)
findings = []
for path in args.paths:
files = [path] if path.is_file() else sorted(path.rglob("*.py"))
for file in files:
findings += scan_source(file.read_text(encoding="utf-8"), file.as_posix())
for name in args.modules:
findings += unresolved(importlib.import_module(name))
for finding in findings:
print(finding)
errors = [f for f in findings if f.code == "ANN4"]
print(f"{len(findings)} findings, {len(errors)} unresolved")
return 1 if errors or (args.strict and findings) else 0
if __name__ == "__main__":
sys.exit(main())
Try it on a small project
The sample project has three files. models.py uses the future import and imports Mailer only for type checkers. service.py has quoted annotations, a call to get_type_hints, and a function whose annotation names something that does not exist.
# sample/shop/__init__.py
# sample/shop/models.py
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING, Annotated, Literal
if TYPE_CHECKING:
from shop.service import Mailer
@dataclass
class Order:
id: int
status: Literal["new", "paid"] = "new"
note: Annotated[str, "free text"] = ""
mailer: Mailer | None = None
parent: Order | None = None
# sample/shop/service.py
import typing
from shop.models import Order
class Mailer:
def send(self, order: "Order") -> "Receipt":
return Receipt()
def history(self) -> list["Receipt"]:
return []
def hints(obj):
return typing.get_type_hints(obj)
class Receipt:
pass
def broken(order: Missing) -> None:
pass
Run the checker from the folder that contains sample. On macOS and Linux the PYTHONPATH setting goes in front of the command; in PowerShell, set $env:PYTHONPATH = "sample" first.
PYTHONPATH=sample venv314/bin/python annocheck.py sample --import shop.models --import shop.service
sample/shop/models.py:2: ANN1 the future import turns every annotation into a string
sample/shop/service.py:8: ANN2 quoted annotation 'Order' can lose its quotes on Python 3.14+
sample/shop/service.py:8: ANN2 quoted annotation 'Receipt' can lose its quotes on Python 3.14+
sample/shop/service.py:11: ANN2 quoted annotation 'Receipt' can lose its quotes on Python 3.14+
sample/shop/service.py:16: ANN3 calls get_type_hints(), which evaluates annotations
shop.models: ANN4 Order: name 'Mailer' is not defined
shop.models: ANN4 Order.__init__: name 'Mailer' is not defined
shop.service: ANN4 broken: name 'Missing' is not defined
8 findings, 3 unresolved
The first line is ANN1: the models file uses the future import. The three ANN2 lines are the quoted names in service.py, and the ANN3 line is its get_type_hints call. Then come the three ANN4 errors. broken names Missing, which exists nowhere. Order and its generated __init__ name Mailer, which exists only inside an if TYPE_CHECKING: block. Under the future import that mistake is invisible until something resolves the hints, and FastAPI and Pydantic both resolve hints when they build their routes and models. The last line counts 8 findings and 3 unresolved names, and the command exits with status 1 because of them.
Test the checker
A checker that is wrong in silence is worse than none, so it gets tests. They cover each finding, the two string cases that must not be reported (Literal values and Annotated metadata), the method and imported-function rules, and the exit codes. One test needs deferred evaluation and is skipped on Python 3.13.
# test_annocheck.py
import importlib
import sys
import pytest
import annocheck
DEFERRED = sys.version_info >= (3, 14)
def codes(source):
return [(f.code, f.line) for f in annocheck.scan_source(source)]
def make_module(tmp_path, monkeypatch, name, source):
(tmp_path / f"{name}.py").write_text(source, encoding="utf-8")
monkeypatch.syspath_prepend(str(tmp_path))
importlib.invalidate_caches()
return importlib.import_module(name)
def test_future_import_is_reported():
assert codes("from __future__ import annotations\n") == [("ANN1", 1)]
def test_other_future_imports_are_ignored():
assert codes("from __future__ import division\n") == []
def test_quoted_parameter_and_return_are_reported():
assert codes('def f(a: "A") -> "B": ...\n') == [("ANN2", 1), ("ANN2", 1)]
def test_quoted_names_inside_generics_and_unions_are_reported():
source = 'x: list["A"] | None\ndef g(p: dict[str, "B"]): ...\ny: "C" | None\n'
assert [code for code, _ in codes(source)] == ["ANN2", "ANN2", "ANN2"]
def test_literal_strings_are_not_forward_references():
assert codes('from typing import Literal\nx: Literal["a", "b"]\n') == []
def test_annotated_metadata_is_not_a_forward_reference():
source = 'from typing import Annotated\nx: Annotated[int, "doc"]\ny: Annotated["A", "doc"]\n'
assert codes(source) == [("ANN2", 3)]
def test_keyword_only_and_variadic_parameters_are_scanned():
assert [c for c, _ in codes('def f(*args: "A", k: "B" = 1, **kw: "C"): ...\n')] == ["ANN2"] * 3
def test_variable_annotation_is_scanned():
assert codes('x: "A" = None\n') == [("ANN2", 1)]
def test_dunder_annotations_read_is_reported():
assert codes("print(f.__annotations__)\n") == [("ANN3", 1)]
def test_get_type_hints_and_signature_calls_are_reported():
source = "import typing, inspect\ntyping.get_type_hints(f)\ninspect.signature(f)\n"
assert codes(source) == [("ANN3", 2), ("ANN3", 3)]
def test_clean_source_has_no_findings():
assert codes("def f(a: int) -> list[str]:\n return []\n") == []
@pytest.mark.skipif(not DEFERRED, reason="needs deferred annotations")
def test_unresolved_name_is_found(tmp_path, monkeypatch):
module = make_module(tmp_path, monkeypatch, "m_missing", "def f(a: Missing) -> None: ...\n")
problems = annocheck.unresolved(module)
assert [p.code for p in problems] == ["ANN4"]
assert "Missing" in problems[0].message
def test_type_checking_only_name_is_found_under_the_future_import(tmp_path, monkeypatch):
source = (
"from __future__ import annotations\n"
"from typing import TYPE_CHECKING\n"
"if TYPE_CHECKING:\n"
" from decimal import Decimal\n"
"def price(x: Decimal) -> None: ...\n"
)
module = make_module(tmp_path, monkeypatch, "m_checking", source)
assert [p.message.split(":")[0] for p in annocheck.unresolved(module)] == ["price"]
def test_method_annotations_are_checked(tmp_path, monkeypatch):
source = "from __future__ import annotations\nclass C:\n def m(self, a: Nope) -> None: ...\n"
module = make_module(tmp_path, monkeypatch, "m_method", source)
assert [p.message.split(":")[0] for p in annocheck.unresolved(module)] == ["C.m"]
def test_resolvable_module_is_clean(tmp_path, monkeypatch):
source = "from __future__ import annotations\nclass A: ...\ndef f(a: A) -> A: ...\n"
module = make_module(tmp_path, monkeypatch, "m_clean", source)
assert annocheck.unresolved(module) == []
def test_functions_imported_from_elsewhere_are_not_blamed(tmp_path, monkeypatch):
make_module(tmp_path, monkeypatch, "m_owner", "from __future__ import annotations\ndef f(a: Nope): ...\n")
user = make_module(tmp_path, monkeypatch, "m_user", "from m_owner import f\n")
assert annocheck.unresolved(user) == []
def test_exit_codes(tmp_path, monkeypatch, capsys):
(tmp_path / "a.py").write_text("from __future__ import annotations\n", encoding="utf-8")
assert annocheck.main([str(tmp_path / "a.py")]) == 0
assert annocheck.main([str(tmp_path / "a.py"), "--strict"]) == 1
make_module(tmp_path, monkeypatch, "m_bad", "from __future__ import annotations\ndef f(a: Nope): ...\n")
assert annocheck.main(["--import", "m_bad"]) == 1
assert "1 unresolved" in capsys.readouterr().out
venv314/bin/python -m pytest -q test_annocheck.py
................. [100%]
17 passed in 0.06s
On Python 3.13.14 the same run prints 16 passed, 1 skipped, and Python 3.15.2 passes all 17.
Prove the tests can fail
Passing tests only matter if they would fail on a broken checker. The next script plants eleven bugs in annocheck.py one at a time, runs the test file against each broken copy, and reports whether the tests noticed. It also runs once without changes as a control.
# mutants.py
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
HERE = Path(__file__).resolve().parent
SOURCE = (HERE / "annocheck.py").read_text(encoding="utf-8")
MUTANTS = [
("literal strings count as forward references", 'if base == "Literal":', "if False:"),
("Annotated metadata counts as a forward reference", "items = items[:1]", "items = items"),
("return annotations are skipped", "if node.returns is not None:", "if False:"),
("keyword-only parameters are skipped", " + a.kwonlyargs", ""),
("variable annotations are skipped", "elif isinstance(node, ast.AnnAssign):", "elif False:"),
("unions are not searched", "elif isinstance(expr, ast.BinOp):", "elif False:"),
("__annotations__ reads are not reported", 'node.attr == "__annotations__"', 'node.attr == "__annotate__"'),
("get_type_hints is replaced by __annotations__", "typing.get_type_hints(target)", "target.__annotations__"),
("imported functions are checked as if local", 'if getattr(obj, "__module__", None) != module.__name__:', "if False:"),
("methods are not checked", "if inspect.isclass(obj):\n targets +=", "if False:\n targets +="),
("exit code is always 0", "return 1 if errors or (args.strict and findings) else 0", "return 0"),
]
def run_tests(source_text):
with tempfile.TemporaryDirectory() as folder:
folder = Path(folder)
(folder / "annocheck.py").write_text(source_text, encoding="utf-8")
shutil.copy(HERE / "test_annocheck.py", folder / "test_annocheck.py")
done = subprocess.run(
[sys.executable, "-m", "pytest", "-q", "-x", "-p", "no:cacheprovider", "test_annocheck.py"],
cwd=folder, capture_output=True, text=True,
)
return done.returncode == 0
print("control (no change):", "passes" if run_tests(SOURCE) else "FAILS")
caught = 0
for label, old, new in MUTANTS:
assert SOURCE.count(old) == 1, (label, SOURCE.count(old))
survived = run_tests(SOURCE.replace(old, new))
caught += not survived
print(f"{'SURVIVED' if survived else 'caught':<9}{label}")
print(f"caught {caught} of {len(MUTANTS)}")
venv314/bin/python mutants.py
control (no change): passes
caught literal strings count as forward references
caught Annotated metadata counts as a forward reference
caught return annotations are skipped
caught keyword-only parameters are skipped
caught variable annotations are skipped
caught unions are not searched
caught __annotations__ reads are not reported
caught get_type_hints is replaced by __annotations__
caught imported functions are checked as if local
caught methods are not checked
caught exit code is always 0
caught 11 of 11
All eleven were caught. In your own project, run annocheck.unresolved from a test for every module in your package, assert that the list is empty, and run that test on both the oldest and the newest Python you support. That one test catches unresolved names, the most common failure in Steps 5 to 7. It does not replace sending a request through each route, which is how Step 7 exposed the FastAPI problem.
Common mistakes and how to check for each
Reading annotations while the module loads
Decorators, metaclasses, and registries that touch __annotations__ or call inspect.signature as classes and functions are created can fail on a name defined further down. Check by importing the module on 3.14, and move the read to first use or switch to Format.FORWARDREF (Step 6).
Treating a dataclass field type as a class
fields(Node)[1].type can be a ForwardRef. Use typing.get_type_hints or get_annotations when you need the class (Step 5).
Assuming a framework resolves forward references the way Python does
Python accepting the file says nothing about FastAPI. Run one request per route (Step 7).
Removing quotes while 3.13 is still supported
Your module will raise NameError at import on 3.13 (Step 1). Run the test suite on every supported version before merging.
Naming a type only under TYPE_CHECKING
That works for type checkers and fails for anything that resolves hints at run time. ANN4 finds it (Step 9).
Writing code against private details
The migration notes tell library authors: “do not read annotations directly from the namespace dictionary attribute of type objects. Use annotationlib.get_annotate_from_class_namespace() during class construction and annotationlib.get_annotations() afterwards.” If you write a metaclass, start there.
Confirm the whole thing works end to end
Run these checks and compare them with what you saw. They take under a minute.
venv314/bin/python step01_forward.pyprints two dictionaries, and the same file on 3.13 ends withNameError: name 'Customer' is not defined.venv314/bin/python step02_lazy.pyprintsafter def : [].venv314/bin/python step08_fastapi.pyshowsshop_lateworking and the other three layouts returning 422.- The
annocheckcommand above prints8 findings, 3 unresolvedand exits with status 1. venv314/bin/python -m pytest -q test_annocheck.pyreports 17 passed, andvenv314/bin/python mutants.pyends withcaught 11 of 11.
If all five match, you have reproduced the behavior described in this tutorial and have a checker you can point at your own code.
Where to go next
Run annocheck.py on one of your own packages on Python 3.13 and 3.14 and read the ANN4 lines first. Then try removing the quotes from one module whose minimum version is 3.14. The PEP 749 text explains the design choices behind annotationlib, including how class bodies and conditional annotations are handled. If you want to see how new language features change real code, the earlier tutorials on Python t-strings and unpacking in comprehensions follow the same measure-first approach, and fixing Python import errors covers the circular imports that often cause forward references in the first place.
Sources and method
Python behavior and quotations come from the official documentation for Python 3.14: the What’s New in Python 3.14 section on deferred evaluation of annotations and its porting notes, the annotationlib module page, the Annotations Best Practices how-to, PEP 649, and PEP 749. The FastAPI excerpt is from the installed 0.165.0 package.
Every script and output in this tutorial was produced by running the files shown, on one Windows 11 machine with CPython 3.13.14, 3.14.10, and 3.15.2 (the last two installed with uv), Pydantic 2.14.4, FastAPI 0.165.0, Starlette 1.10.0, httpx 0.28.1, and pytest 9.2.0. I did not test macOS, Linux, the free-threaded build, the typing_extensions backport, or Pydantic and FastAPI on Python 3.15. The benchmark uses a synthetic module and is one machine’s median of 15 fresh processes. Library behavior can change with a new release, so rerun Steps 7 and 8 after upgrading.








No Comment! Be the first one.