Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readPython
#Python#Type Hints#FastAPI#Migration
A deferred annotation capsule with a forward-reference arrow and an empty name slot, headline PEP 649

Introduction & Quick Summary

Symptom. The application starts, imports cleanly, and the first request fails:

code
Traceback (most recent call last): File "/app/main.py", line 42, in get_filtered_items ... NameError: name 'gh_user_mod' is not defined

The 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.

bash
pip install "fastapi>=0.128.1" "pydantic>=2.11" "sqlalchemy>=2.0.36"
python
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:

python
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 defined

That 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:

python
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

BehaviourPython 3.13Python 3.14Action
Annotation evaluationat definition timedeferred until readnothing, usually
__annotations__ valueevaluated objectslazy proxyread via annotationlib
from __future__ import annotationsturns them into stringsstill accepted, no longer neededremove after upgrade
typing.get_type_hints()may raisemay raiseuse Format.FORWARDREF
asyncio.get_event_loop() without a loopcreates one, warnsraises RuntimeErrorasyncio.run() or get_running_loop()
bool(NotImplemented)TrueTypeErrorcompare with is NotImplemented
return inside finallyallowedSyntaxWarningrestructure the block
multiprocessing default start methodfork on Linuxforkserver on Linuxpass state explicitly
Reader of annotationsBreaks on 3.14Minimum version that handles it
FastAPI endpoint signaturesyes with TYPE_CHECKING imports0.128.1
Pydantic modelsedge cases with forward references2.11
dataclassesonly with unresolvable namescall get_type_hints yourself
SQLAlchemy Mapped[]yes for string-mapped types2.0.36
attrssame mechanism24.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:

bash
grep -rn "if TYPE_CHECKING" --include=*.py . | cut -d: -f1 | sort -u

Only 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.

bash
# 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 2

Tests 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:

python
# 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:

python
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:

python
try: do_work() finally: cleanup() return result # discards any exception from do_work

Move 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:

bash
uv venv --python 3.14 uv pip install --only-binary :all: -r requirements.txt pytest -W error::DeprecationWarning

The 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_CHECKING imports 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 annotations in 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-python are 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 RuntimeError from get_event_loop as a bug in the library. It is the documented removal; the caller owns the loop now.
  • Ignoring the finally warning. 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 documentation

The Python documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.