Skip to content

Commit 76c8f7b

Browse files
author
atzander_a
committed
feat: support Pydantic descriptions
1 parent f636bfe commit 76c8f7b

File tree

3 files changed

+27
-1
lines changed

3 files changed

+27
-1
lines changed

pdoc/_pydantic.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,13 @@ def default_value(parent: ClassOrModule, name: str, obj: Any) -> Any:
4747
return obj
4848

4949

50+
def get_computed_field_docstring(parent: ClassOrModule, field_name: str) -> str | None:
51+
if is_pydantic_model(parent):
52+
if field := parent.__pydantic_computed_fields__.get(field_name, None):
53+
return field.description
54+
return None
55+
56+
5057
def get_field_docstring(parent: ClassOrModule, field_name: str) -> str | None:
5158
if is_pydantic_model(parent):
5259
if field := parent.__pydantic_fields__.get(field_name, None):

pdoc/doc.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -327,8 +327,19 @@ def members(self) -> dict[str, Doc]:
327327
taken_from=taken_from,
328328
)
329329

330-
if _doc := _pydantic.get_field_docstring(cast(type, self.obj), name):
330+
## Try get docstring from Pydantic field.
331+
if _doc := _pydantic.get_field_docstring(
332+
cast(type, self.obj),
333+
name,
334+
):
335+
doc.docstring = _doc
336+
## Try get docstring from Pydantic computed field.
337+
elif _doc := _pydantic.get_computed_field_docstring(
338+
cast(type, self.obj),
339+
name,
340+
):
331341
doc.docstring = _doc
342+
332343
elif self._var_docstrings.get(name):
333344
doc.docstring = self._var_docstrings[name]
334345
elif self._func_docstrings.get(name) and not doc.docstring:

test/test__pydantic.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,18 @@ class ExampleModel(pydantic.BaseModel):
1616
id: int
1717
name: str = pydantic.Field(description="desc", default="Jane Doe")
1818

19+
@pydantic.computed_field(description="computed")
20+
@property
21+
def computed(self) -> str:
22+
return "computed_value"
23+
1924

2025
def test_with_pydantic(monkeypatch):
2126
assert _pydantic.is_pydantic_model(ExampleModel)
2227
assert _pydantic.get_field_docstring(ExampleModel, "name") == "desc"
28+
assert (
29+
_pydantic.get_computed_field_docstring(ExampleModel, "computed") == "computed"
30+
)
2331
assert _pydantic.default_value(ExampleModel, "name", None) == "Jane Doe"
2432

2533
assert not _pydantic.is_pydantic_model(pdoc.doc.Module)

0 commit comments

Comments
 (0)