Skip to content

Commit b2129b4

Browse files
committed
Adding field-show-examples to show the examples for a field
1 parent 98cdedd commit b2129b4

File tree

9 files changed

+157
-0
lines changed

9 files changed

+157
-0
lines changed

docs/source/users/configuration.rst

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -502,6 +502,17 @@ Fields
502502
Displays all constraints that are associated with the given pydantic field.
503503

504504

505+
.. config_description:: autopydantic_model
506+
:title: Show Examples
507+
:path: target.configuration.FieldShowExamples
508+
:confpy: autodoc_pydantic_field_show_examples
509+
:directive_option: field-show-examples
510+
:enable: members, field-doc-policy=docstring
511+
:values: True, False
512+
513+
Displays all examples that are associated with the given pydantic field.
514+
515+
505516
.. config_description:: autopydantic_model
506517
:title: Show Alias
507518
:path: target.configuration.FieldShowAlias

sphinxcontrib/autodoc_pydantic/application.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,11 @@ def full_name(self) -> str:
254254
default='field',
255255
types=str,
256256
),
257+
Config(
258+
name='field_show_examples',
259+
default=True,
260+
types=bool,
261+
),
257262

258263
# general
259264
Config(

sphinxcontrib/autodoc_pydantic/directives/autodocumenters.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -826,6 +826,24 @@ def add_content(
826826
if self.pydantic.options.is_true('field-list-validators'):
827827
self.add_validators()
828828

829+
if self.pydantic.options.is_true('field-show-examples'):
830+
self.add_examples()
831+
832+
def add_examples(self) -> None:
833+
"""Add section showing all defined examples for field."""
834+
835+
field_name = self.pydantic_field_name
836+
examples = self.pydantic.inspect.fields.get_examples(field_name)
837+
838+
if examples:
839+
source_name = self.get_sourcename()
840+
self.add_line(':Examples:', source_name)
841+
for value in examples:
842+
line = f' - {value}'
843+
self.add_line(line, source_name)
844+
845+
self.add_line('', source_name)
846+
829847
def add_constraints(self) -> None:
830848
"""Adds section showing all defined constraints."""
831849

sphinxcontrib/autodoc_pydantic/directives/options/definition.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
'field-list-validators': option_default_true,
2929
'field-swap-name-and-alias': option_default_true,
3030
'field-doc-policy': option_one_of_factory(OptionsFieldDocPolicy.values()),
31+
'field-show-examples': option_default_true,
3132
'__doc_disable_except__': option_list_like,
3233
}
3334
"""Represents added directive options for :class:`PydanticFieldDocumenter`."""

sphinxcontrib/autodoc_pydantic/inspection.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,17 @@ def get_constraints(self, field_name: str) -> dict[str, Any]:
164164
if getattr(meta, key) is not None
165165
}
166166

167+
def has_examples(self, field_name:str) -> bool:
168+
"""Check if examples are provided in field info."""
169+
170+
return self.get_property_from_field_info(field_name, "examples") is not None
171+
172+
def get_examples(self, field_name: str) -> list[Any]:
173+
"""Get examples for given `field_name`."""
174+
175+
if self.has_examples(field_name):
176+
return self.get_property_from_field_info(field_name, 'examples')
177+
167178
def is_required(self, field_name: str) -> bool:
168179
"""Check if a given pydantic field is required/mandatory. Returns True,
169180
if a value for this field needs to provided upon model creation.

tests/conftest.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
'autodoc_pydantic_validator_list_fields': False,
5151
'autodoc_pydantic_field_list_validators': False,
5252
'autodoc_pydantic_field_show_constraints': False,
53+
'autodoc_pydantic_field_show_examples': False,
5354
'autodoc_pydantic_field_show_alias': False,
5455
'autodoc_pydantic_field_show_required': False,
5556
'autodoc_pydantic_field_show_optional': False,

tests/roots/test-base/target/configuration.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -587,6 +587,20 @@ class FieldSwapNameAndAlias(BaseModel):
587587
"""Field1"""
588588

589589

590+
class FieldShowExamples(BaseModel):
591+
"""FieldShowExamples."""
592+
593+
field: int = Field(1, examples=[2, 3])
594+
"""Field."""
595+
596+
597+
class FieldShowExamplesExtra(BaseModel):
598+
"""FieldShowExamplesExtra."""
599+
600+
field: int = Field(1, examples=[2, 3], json_schema_extra=dict(examples=[4, 5]))
601+
"""Field."""
602+
603+
590604
class ModelErdanticFigureRelated(ModelShowFieldSummary):
591605
"""ModelErdanticFigureRelated."""
592606

tests/roots/test-base/target/usage_automodule.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,10 @@ class AutoModuleSettings(BaseSettings):
2121
default=5, ge=0, le=100, description='Shows constraints within doc string.'
2222
)
2323

24+
field_with_examples: int = Field(0, examples=[123, 546, 789])
25+
"""Shows examples within doc string."""
26+
27+
2428
@field_validator('field_with_validator_and_alias', 'field_plain_with_validator')
2529
def check_max_length_ten(cls, v):
2630
"""Show corresponding field with link/anchor."""

tests/test_configuration_fields.py

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1632,3 +1632,95 @@ def test_autodoc_pydantic_field_swap_name_and_alias_true_directive_global(parse_
16321632
},
16331633
)
16341634
assert_node(doctree, output_nodes)
1635+
1636+
1637+
def test_autodoc_pydantic_field_show_examples_true(autodocument):
1638+
kwargs = dict(
1639+
object_path='target.configuration.FieldShowExamples.field', **KWARGS
1640+
)
1641+
1642+
result = [
1643+
'',
1644+
'.. py:pydantic_field:: FieldShowExamples.field',
1645+
' :module: target.configuration',
1646+
' :type: int',
1647+
'',
1648+
' Field.',
1649+
'',
1650+
' :Examples:',
1651+
' - 2',
1652+
' - 3',
1653+
'',
1654+
]
1655+
1656+
# explicit local
1657+
actual = autodocument(options_doc={'field-show-examples': True}, **kwargs)
1658+
assert result == actual
1659+
1660+
# explicit local overwrite global
1661+
actual = autodocument(
1662+
options_app={'autodoc_pydantic_field_show_examples': False},
1663+
options_doc={'field-show-examples': True},
1664+
**kwargs,
1665+
)
1666+
assert result == actual
1667+
1668+
1669+
def test_autodoc_pydantic_field_show_examples_false(autodocument):
1670+
kwargs = dict(
1671+
object_path='target.configuration.FieldShowExamples.field', **KWARGS
1672+
)
1673+
1674+
result = [
1675+
'',
1676+
'.. py:pydantic_field:: FieldShowExamples.field',
1677+
' :module: target.configuration',
1678+
' :type: int',
1679+
'',
1680+
' Field.',
1681+
'',
1682+
]
1683+
1684+
# explicit local
1685+
actual = autodocument(options_doc={'field-show-examples': False}, **kwargs)
1686+
assert result == actual
1687+
1688+
# explicit local overwrite global
1689+
actual = autodocument(
1690+
options_app={'autodoc_pydantic_field_show_examples': True},
1691+
options_doc={'field-show-examples': False},
1692+
**kwargs,
1693+
)
1694+
assert result == actual
1695+
1696+
1697+
def test_autodoc_pydantic_field_show_examples_ignore_extra(autodocument):
1698+
kwargs = dict(
1699+
object_path='target.configuration.FieldShowExamplesExtra.field', **KWARGS
1700+
)
1701+
1702+
result = [
1703+
'',
1704+
'.. py:pydantic_field:: FieldShowExamplesExtra.field',
1705+
' :module: target.configuration',
1706+
' :type: int',
1707+
'',
1708+
' Field.',
1709+
'',
1710+
' :Examples:',
1711+
' - 2',
1712+
' - 3',
1713+
'',
1714+
]
1715+
1716+
# explicit local
1717+
actual = autodocument(options_doc={'field-show-examples': True}, **kwargs)
1718+
assert result == actual
1719+
1720+
# explicit local overwrite global
1721+
actual = autodocument(
1722+
options_app={'autodoc_pydantic_field_show_examples': False},
1723+
options_doc={'field-show-examples': True},
1724+
**kwargs,
1725+
)
1726+
assert result == actual

0 commit comments

Comments
 (0)