Skip to content

fix: Forward reference resolution with decorated functions#1640

Open
nickcatal wants to merge 2 commits intovitalik:masterfrom
nickcatal:fix/pydantic-create-model-forward-refs
Open

fix: Forward reference resolution with decorated functions#1640
nickcatal wants to merge 2 commits intovitalik:masterfrom
nickcatal:fix/pydantic-create-model-forward-refs

Conversation

@nickcatal
Copy link
Copy Markdown

Fixes #1424

Problem

from __future__ import annotations with decorated functions (e.g. @paginate) causes Schema parameters to be incorrectly detected as query parameters.

Solution

Two complementary fixes:

  1. Set __module__ parameter on create_model() to provide namespace context for Pydantic v2
  2. Unwrap decorated functions in get_typed_signature() to get correct __globals__ for string annotation resolution

Both changes are required for complete forward reference support with decorators.

Tests

Added two tests in test_signature_details.py:

  • test_parameter_model_has_view_module - Verifies __module__ parameter
  • test_decorated_function_resolves_string_annotations - Verifies decorated function annotation resolution

All CI checks pass (ruff, mypy, pytest).

Replaces type() with pydantic.create_model() when dynamically creating
parameter models. This fixes PydanticUserError when using request body
schemas with forward references in Pydantic v2.

The type() approach doesn't properly resolve forward references, causing
errors like 'BodyParams is not fully defined'. Using create_model()
ensures Pydantic's model creation machinery properly handles forward
references and validates schema definitions.

Resolves the TODO comment at line 183 that suggested investigating
create_model() for special handling.
Two complementary fixes for forward reference resolution:

1. Set __module__ on create_model() to provide namespace context
   for Pydantic v2 to resolve references

2. Unwrap decorated functions to get correct __globals__ so string
   annotations can resolve to actual schema classes

Both changes are required for complete forward reference support.
@nickcatal
Copy link
Copy Markdown
Author

@vitalik any way we can get this merged in? Thanks!

@nickcatal
Copy link
Copy Markdown
Author

@vitalik just checking in to see if we can get this in trunk, thanks!

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.

[BUG] Endpoint with query schema crashes when paginated and from __future__ import annotations import included

1 participant