Browse Source

🐛 Fix unhashable `Annotated` type in `get_definitions` OpenAPI schema generation

`get_definitions()` uses a set comprehension to collect field annotations
for deduplication. However, on Python 3.14 with Pydantic v2.13+, some
`Annotated` types contain `FieldInfoMetadata` objects that are not
hashable, causing a `TypeError`:

    TypeError: cannot use 'typing._AnnotatedAlias' as a set element
    (unhashable type: 'FieldInfoMetadata')

This is triggered when routes use `Annotated` parameters with metadata
such as `Query(max_length=..., description=...)` or similar constructs
that produce unhashable Pydantic field metadata.

Fix: use `id()` for identity-based deduplication instead of relying on
`__hash__` of annotation objects. Since annotations are interned type
objects, `id()` comparison is semantically equivalent for this filtering
purpose.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
pull/15429/head
Yuerchu 3 months ago
parent
commit
9e69d8b6fe
No known key found for this signature in database GPG Key ID: 7ADEA2D27613926
  1. 4
      fastapi/_compat/v2.py

4
fastapi/_compat/v2.py

@ -317,9 +317,9 @@ def get_definitions(
for model in flat_serialization_models for model in flat_serialization_models
] ]
flat_model_fields = flat_validation_model_fields + flat_serialization_model_fields flat_model_fields = flat_validation_model_fields + flat_serialization_model_fields
input_types = {f.field_info.annotation for f in fields} input_type_ids = {id(f.field_info.annotation) for f in fields}
unique_flat_model_fields = { unique_flat_model_fields = {
f for f in flat_model_fields if f.field_info.annotation not in input_types f for f in flat_model_fields if id(f.field_info.annotation) not in input_type_ids
} }
inputs = [ inputs = [
( (

Loading…
Cancel
Save