Skip to content

Raise clear NameError at route registration for unresolvable forward-reference annotations#15307

Open
Dima-Bulavenko wants to merge 4 commits intofastapi:masterfrom
Dima-Bulavenko:unresolable_annotations
Open

Raise clear NameError at route registration for unresolvable forward-reference annotations#15307
Dima-Bulavenko wants to merge 4 commits intofastapi:masterfrom
Dima-Bulavenko:unresolable_annotations

Conversation

@Dima-Bulavenko
Copy link
Copy Markdown

This PR is related to #13056

Problem

When from __future__ import annotations is used and a type isn't available at route registration time (e.g. defined after the route, or imported only under TYPE_CHECKING), FastAPI silently swallows the unresolved forward reference. This leads to wrong behavior when unresolved annotation of a parameter quietly becomes a query parameter . The actual error only shows up later as a Pydantic error failure when the route is called or docs are generated.

I looked into fully fixing #13056 and IMO the only solutions to fix it is by deferring annotation resolution to request time, but that would mean rewriting large parts of route initializator for such minor issue.

Solution

Instead of silently producing wrong behavior, fail immediately at route registration with a clear error message that tells the developer what went wrong and how to fix it.

What changed

  • Repalce deprecated eval_type_lenient to try_eval_type
  • Implement error throwing in get_typed_annotation function is ForwardRef annotation wasn't resolved
  • Create tests for get_typed_annotation and for routes with valida and invalid types

@codspeed-hq
Copy link
Copy Markdown

codspeed-hq bot commented Apr 6, 2026

Merging this PR will not alter performance

✅ 20 untouched benchmarks


Comparing Dima-Bulavenko:unresolable_annotations (5bdfa02) with master (c3c9dd6)

Open in CodSpeed

@Dima-Bulavenko Dima-Bulavenko marked this pull request as draft April 6, 2026 08:38
@Dima-Bulavenko Dima-Bulavenko marked this pull request as ready for review April 6, 2026 17:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant