Skip to content

Commit f14b7da

Browse files
authored
Preserve field description when rebuilding model fields (#11698)
1 parent 04fd639 commit f14b7da

File tree

2 files changed

+24
-4
lines changed

2 files changed

+24
-4
lines changed

pydantic/_internal/_fields.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -319,18 +319,20 @@ def rebuild_model_fields(
319319
if field_info._complete:
320320
rebuilt_fields[f_name] = field_info
321321
else:
322+
existing_desc = field_info.description
322323
ann = _typing_extra.eval_type(
323324
field_info._original_annotation,
324325
*ns_resolver.types_namespace,
325326
)
326327
ann = _generics.replace_types(ann, typevars_map)
327328

328329
if (assign := field_info._original_assignment) is PydanticUndefined:
329-
rebuilt_fields[f_name] = FieldInfo_.from_annotation(ann, _source=AnnotationSource.CLASS)
330+
new_field = FieldInfo_.from_annotation(ann, _source=AnnotationSource.CLASS)
330331
else:
331-
rebuilt_fields[f_name] = FieldInfo_.from_annotated_attribute(
332-
ann, assign, _source=AnnotationSource.CLASS
333-
)
332+
new_field = FieldInfo_.from_annotated_attribute(ann, assign, _source=AnnotationSource.CLASS)
333+
# The description might come from the docstring if `use_attribute_docstrings` was `True`:
334+
new_field.description = new_field.description if new_field.description is not None else existing_desc
335+
rebuilt_fields[f_name] = new_field
334336

335337
return rebuilt_fields
336338

tests/test_fields.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,3 +170,21 @@ class Model(BaseModel):
170170
field: str = Field(coerce_numbers_to_str=True)
171171

172172
assert Model(field=number).field == str(number)
173+
174+
175+
def test_rebuild_model_fields_preserves_description() -> None:
176+
"""https://github.com/pydantic/pydantic/issues/11696"""
177+
178+
class Model(BaseModel):
179+
model_config = ConfigDict(use_attribute_docstrings=True)
180+
181+
f: 'Int'
182+
"""test doc"""
183+
184+
assert Model.model_fields['f'].description == 'test doc'
185+
186+
Int = int
187+
188+
Model.model_rebuild()
189+
190+
assert Model.model_fields['f'].description == 'test doc'

0 commit comments

Comments
 (0)