Python 3.14 PEP 649: NameError from lazy annotations
Annotations are no longer strings. A NAME only imported under TYPE_CHECKING now raises when FastAPI or Pydantic reads the signature.

Introduction & Quick Summary
Symptom. The application starts, imports cleanly, and the first request fails:
Traceback (most recent call last):
File "/app/main.py", line 42, in get_filtered_items
...
NameError: name 'gh_user_mod' is not definedThe name it cannot find is inside a type annotation, and it was imported under if TYPE_CHECKING:. Nothing in that file changed; only the Python version did. In another corner you get TypeError: 'NotImplementedType' object is not callable from a comparison helper, or a SyntaxWarning about control flow in a finally block.
Cause. Python 3.14 implements PEP 649: annotations are no longer evaluated at definition time and no longer stored as the strings from __future__ import annotations produced. They are lazily computed by a new annotationlib layer, and anything that asks for them — FastAPI building an endpoint signature, Pydantic validating a model, dataclasses, SQLAlchemy's Mapped[] — triggers evaluation at that moment. A name that exists only for the type checker then does not exist at runtime.
Fix. Upgrade the frameworks that inspect annotations, then let them ask for forward references instead of full values.
pip install "fastapi>=0.128.1" "pydantic>=2.11" "sqlalchemy>=2.0.36"from annotationlib import Format, get_annotations
# this does not raise even though Undefined is not importable
def handler(payload: Undefined) -> None: ...
print(get_annotations(handler, format=Format.FORWARDREF))
# {'payload': ForwardRef('Undefined', owner=<function handler ...>)}Core Mechanics, Signatures & Reproducible Setup
Before 3.14, an annotation was evaluated when the def executed, and from __future__ import annotations changed it into a string that was never evaluated. PEP 649 replaces both mechanisms: the annotation is a compiler-generated function that runs only when someone reads it, and annotationlib offers three ways to read it — VALUE (evaluate, may raise), FORWARDREF (substitute markers for unknown names) and STRING (the source text).
Reproduce the failure without a framework:
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from models import Order # never imported at runtime
def total(order: Order) -> int: # fine on 3.14: annotation is deferred
return 0
from typing import get_type_hints
get_type_hints(total) # NameError: name 'Order' is not definedThat is exactly what a framework does at startup or on first request. The fix is not to remove the TYPE_CHECKING import: it is to make the reader resilient, which recent FastAPI does by inspecting with FORMAT.FORWARDREF and resolving only what it needs.
The three formats behave differently and the difference is the whole migration:
import annotationlib
class Undefined: # pretend this name is not defined
pass
def func(arg: "Missing") -> None: ...
annotationlib.get_annotations(func, format=annotationlib.Format.FORWARDREF)
annotationlib.get_annotations(func, format=annotationlib.Format.STRING)get_type_hints() still defaults to full evaluation, which is why user code that calls it in a hot path now fails where it used to return strings.
Key Comparison Table
| Behaviour | Python 3.13 | Python 3.14 | Action |
|---|---|---|---|
| Annotation evaluation | at definition time | deferred until read | nothing, usually |
__annotations__ value | evaluated objects | lazy proxy | read via annotationlib |
from __future__ import annotations | turns them into strings | still accepted, no longer needed | remove after upgrade |
typing.get_type_hints() | may raise | may raise | use Format.FORWARDREF |
asyncio.get_event_loop() without a loop | creates one, warns | raises RuntimeError | asyncio.run() or get_running_loop() |
bool(NotImplemented) | True | TypeError | compare with is NotImplemented |
return inside finally | allowed | SyntaxWarning | restructure the block |
multiprocessing default start method | fork on Linux | forkserver on Linux | pass state explicitly |
| Reader of annotations | Breaks on 3.14 | Minimum version that handles it |
|---|---|---|
| FastAPI endpoint signatures | yes with TYPE_CHECKING imports | 0.128.1 |
| Pydantic models | edge cases with forward references | 2.11 |
| dataclasses | only with unresolvable names | call get_type_hints yourself |
SQLAlchemy Mapped[] | yes for string-mapped types | 2.0.36 |
| attrs | same mechanism | 24.x |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. TYPE_CHECKING imports are the breakage point
Grepping for the pattern tells you where to look before you deploy:
grep -rn "if TYPE_CHECKING" --include=*.py . | cut -d: -f1 | sort -uOnly the names used in annotations that a framework inspects matter. A TYPE_CHECKING import used inside a function body under cast() is harmless. The dangerous ones are endpoint parameters, Pydantic field types and ORM column annotations. When a name has to exist at runtime, move the import out of the guard and make the cycle go away with a local import inside the function that needs it.
2. The FastAPI ordering trap
Mergify's migration write-up is the clearest example of the sequencing: bump the framework before removing the quotes. FastAPI 0.128.1 uses Format.FORWARDREF when inspecting endpoints, so quoted annotations and TYPE_CHECKING imports keep working. Removing the quotes first, while still on 0.128.0, breaks every endpoint at startup instead of at first request.
# 1
pip install -U "fastapi>=0.128.1"
# 2
# upgrade the interpreter in CI and the base image
# 3
ruff check --select UP --fix # optional cosmetics, after 1 and 2Tests may not catch this because they exercise responses, not signature resolution. Add one test that imports the app and hits app.openapi(), which forces every endpoint signature to be read.
3. asyncio.get_event_loop() no longer creates a loop
The same release removed the implicit loop creation, so code that called get_event_loop() outside a running loop now raises RuntimeError: There is no current event loop in thread 'MainThread'. This is the most common 3.14 runtime break in CLI tools and synchronous wrappers around async libraries:
# before
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
# after
asyncio.run(main())
# inside an async function
loop = asyncio.get_running_loop()Library code that cached a loop at import time has to become lazy, and pytest plugins that created loops for fixtures need pytest-asyncio 1.x or the asyncio_mode = auto setting.
4. multiprocessing defaults to forkserver
On Linux, the default start method changed from fork to forkserver. A child no longer inherits the parent's globals, so a worker function that relied on a module-level database handle, a logger or a loaded model now raises or silently misbehaves:
import multiprocessing as mp
def worker(item, config): # pass what the child needs
return item * config["factor"]
if __name__ == "__main__":
ctx = mp.get_context("forkserver")
with ctx.Pool(4) as pool:
print(pool.map(worker, range(4), [{"factor": 2}] * 4))fork is still available through get_context("fork"), but it is unsafe with threads and deprecation is likely. Passing state explicitly is the durable fix, and it is also what makes the code work on macOS, where spawn has been the default since 3.8.
5. finally control flow now warns
PEP 765 makes a return, break or continue that leaves a finally block emit SyntaxWarning, because it silently discards an in-flight exception. Under -W error the module fails to import:
try:
do_work()
finally:
cleanup()
return result # discards any exception from do_workMove the assignment out of the block and return after it. Filters can silence the warning, but a filter hides exactly the bug the warning was added for.
6. Checking imports and wheels before the switch
C extensions must ship cp314 wheels; anything that has to compile on install needs a toolchain in the image. Run the check with binary wheels only:
uv venv --python 3.14
uv pip install --only-binary :all: -r requirements.txt
pytest -W error::DeprecationWarningThe free-threaded build (python3.14t) is a separate interpreter, not the default: importing an extension that has not been ported silently re-enables the GIL, which shows up as no speedup rather than as an error. Convert the container image, setup-python version and requires-python together, or CI and production disagree in a way that only shows on the endpoint that used the annotation.
Common Compilation/Runtime Mistakes & Version Gotchas
- Deleting
TYPE_CHECKINGimports first. The guard was correct; the reader was not. Upgrade the reader. - Assuming a green test suite proves the migration. Signature resolution happens on first request or at OpenAPI generation, not at import.
- Leaving
from __future__ import annotationsin place. It still works, but it prevents 3.14's faster annotation handling and confuses readers about which model is in force. - Pinning only the runtime. The Docker base image, CI matrix and
requires-pythonare three places that must match. - Reusing an old virtualenv. Recreate it; a 3.13 environment with 3.14 packages produces import errors that look like dependency bugs.
- Treating the
RuntimeErrorfromget_event_loopas a bug in the library. It is the documented removal; the caller owns the loop now. - Ignoring the
finallywarning. Suppressing it keeps a real exception-swallowing bug in place.
Format the annotations you inspect with the JSON formatter when a Pydantic error message embeds a schema, and diff the old and new OpenAPI output with the text diff tool to confirm no field silently changed type.
Reference: What's new in Python 3.14 and the annotationlib documentation.
Official references
primary documentationThe Python documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesasyncpg DuplicatePreparedStatement on PgBouncer and Supabase
asyncpg caches prepared statements per connection while a transaction pooler rotates connections underneath it. The cache setting, pool sizing and retry that fix it.
Python Tabulate: Markdown Grid Headers and Alignment
Use Python's tabulate library to format Markdown tables, set custom headers, and control column alignment with pipe and grid formats.
Django select_related and prefetch_related: Fix N+1 Queries
Learn how to eliminate N+1 queries in Django with select_related and prefetch_related, including practical examples, when to use each, and common pitfalls.
Python f-string format specifier: syntax and examples
How to use Python f-string format specifiers for alignment, numeric precision, grouping, and sign control, with practical examples.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.