API

Structure

The following API documentation does not include all modules of autodoc_pydantic. Instead, it focuses only on modules that are relevant for documentation purposes:

autodoc_pydantic
|
|- __init__.py
|- inspection.py
|- utility.py
|
+--directives
   |- __init__.py
   |- autodocumenters.py
   |- directives.py
   |- templates.py
   |- utility.py
   |
   \--options
      |- __init__.py
      |- composites.py
      |- definition.py
      |- enums.py
      \- validators.py

For everything else, please refer to the source code directly.

Modules

inspection.py

This module is located at sphinxcontrib/autodoc_pydantic/inspection.py.

This module contains the inspection functionality for pydantic models. It is used to retrieve relevant information about fields, validators, config and schema of pydantical models.

class ValidatorFieldMap(field_name: str, validator_name: str, model_ref: str)[source]

Bases: tuple

Contains single mapping of a pydantic validator and field.

property field_name

Name of the field.

property validator_name

Name of the validator.

property model_ref

Reference corresponding parent pydantic model.

property field_ref

Reference to field..

property validator_ref

Reference to validator.

class BaseInspectionComposite(parent: sphinxcontrib.autodoc_pydantic.inspection.ModelInspector)[source]

Bases: object

Serves as base class for inspector composites which are coupled to ModelInspector instances. Each composite provides a separate namespace to handle different areas of pydantic models (e.g. fields and validators).

class FieldInspector(parent: sphinxcontrib.autodoc_pydantic.inspection.ModelInspector)[source]

Bases: sphinxcontrib.autodoc_pydantic.inspection.BaseInspectionComposite

Provide namespace for inspection methods for fields of pydantic models.

property validator_names: Dict[str, Set[str]]

Return mapping between all field names (keys) and their corresponding validator names (values).

property validator_names_root: Dict[str, Set[str]]

Return mapping between all field names (keys) and their corresponding validator names (values) for root validators only.

property validator_names_standard: Dict[str, List[str]]

Return mapping between all field names (keys) and their corresponding validator names (values) for standard validators only.

Please be aware, the asterisk field name * is used to represent all fields.

property names: List[str]

Return field names while keeping ordering.

get(name: str) pydantic.fields.ModelField[source]

Get the instance of ModelField for given field name.

get_property_from_field_info(field_name: str, property_name: str) Any[source]

Get specific property value from pydantic’s field info.

get_constraints(field_name: str) Dict[str, Any][source]

Get constraints for given field_name.

is_required(field_name: str) bool[source]

Check if a given pydantic field is required/mandatory. Returns True, if a value for this field needs to provided upon model creation.

is_json_serializable(field_name: str) bool[source]

Check if given pydantic field is JSON serializable by calling pydantic’s model.json() method. Custom objects might not be serializable and hence would break JSON schema generation.

property non_json_serializable: List[str]

Get all fields that can’t be safely JSON serialized.

class ValidatorInspector(parent: sphinxcontrib.autodoc_pydantic.inspection.ModelInspector)[source]

Bases: sphinxcontrib.autodoc_pydantic.inspection.BaseInspectionComposite

Provide namespace for inspection methods for validators of pydantic models.

static get_names_from_wrappers(validators: Iterator[pydantic.class_validators.Validator]) Set[str][source]

Return the actual validator names as defined in the class body from list of pydantic validator wrappers.

Parameters

validators (list) – Wrapper objects for pydantic validators.

property names_root_validators: Set[str]

Return all names of root validators.

property names_asterisk_validators: Set[str]

Return all names of asterisk validators. Asterisk are defined as validators, that process all availble fields. They consist of root validators and validators with the * field target.

property names_standard_validators: Set[str]

Return all names of standard validators which do not process all fields at once (in contrast to asterisk validators).

property names: Set[str]

Return names of all validators of pydantic model.

is_asterisk(name: str) bool[source]

Check if provided validator name references an asterisk validator.

Parameters

name (str) – Name of the validator.

class ConfigInspector(parent: sphinxcontrib.autodoc_pydantic.inspection.ModelInspector)[source]

Bases: sphinxcontrib.autodoc_pydantic.inspection.BaseInspectionComposite

Provide namespace for inspection methods for config class of pydantic models.

property is_configured: bool

Check if pydantic model config was explicitly configured. If not, it defaults to the standard configuration provided by pydantic and typically does not required documentation.

property items: Dict

Return all non private (without leading underscore _) items of pydantic configuration class.

class ReferenceInspector(*args, **kwargs)[source]

Bases: sphinxcontrib.autodoc_pydantic.inspection.BaseInspectionComposite

Provide namespace for inspection methods for creating references mainly between pydantic fields and validators.

Importantly, mappings provides the set of all ValidatorFieldMap instances which contain all references between fields and validators.

property model_path: str

Retrieve the full path of the model.

create_model_reference(name: str) str[source]

Create reference for given attribute name returning full path including the model path.

filter_by_validator_name(name: str) List[sphinxcontrib.autodoc_pydantic.inspection.ValidatorFieldMap][source]

Return mappings for given validator name.

filter_by_field_name(name: str) List[sphinxcontrib.autodoc_pydantic.inspection.ValidatorFieldMap][source]

Return mappings for given field name.

class SchemaInspector(parent: sphinxcontrib.autodoc_pydantic.inspection.ModelInspector)[source]

Bases: sphinxcontrib.autodoc_pydantic.inspection.BaseInspectionComposite

Provide namespace for inspection methods for general properties of pydantic models.

property sanitized: Dict

Get model’s schema while handling non serializable fields. Such fields will be replaced by TypeVars.

create_sanitized_model() pydantic.main.BaseModel[source]

Generates a new pydantic model from the original one while substituting invalid fields with typevars.

class StaticInspector[source]

Bases: object

Namespace under ModelInspector for static methods.

static is_pydantic_model(obj: Any) bool[source]

Determine if object is a valid pydantic model.

classmethod is_validator_by_name(name: str, obj: Any) bool[source]

Determine if a validator is present under provided name for given model.

class ModelInspector(model: Type[pydantic.main.BaseModel])[source]

Bases: object

Provides inspection functionality for pydantic models.

static

alias of sphinxcontrib.autodoc_pydantic.inspection.StaticInspector

classmethod from_signode(signode: sphinx.addnodes.desc_signature) sphinxcontrib.autodoc_pydantic.inspection.ModelInspector[source]

Create instance from a signode as used within sphinx directives.

autodocumenters.py

This module is located at sphinxcontrib/autodoc_pydantic/directives/autodocumenters.py.

This module contains autodoc_pydantic’s autodocumenters.

class PydanticAutoDoc(documenter: sphinx.ext.autodoc.Documenter, is_child: bool)[source]

Bases: object

Composite to provide single namespace to access all autodoc_pydantic relevant documenter directive functionalities.

property options: sphinxcontrib.autodoc_pydantic.directives.options.composites.AutoDocOptions

Provides access to PydanticDocumenterOptions to handle global and local configuration settings.

property inspect: sphinxcontrib.autodoc_pydantic.inspection.ModelInspector

Provides ModelInspector to access all inspection methods. You may wonder why this inspect is a property instead of a simple attribute being defined in the __init__ method of this class. The reason is the following: auto-documenters do not have their object attribute being correctly set after instantiation which typically holds a reference to the corresponding pydantic model and objects to be documented. Instead, object is None after plain instantiation (executing __init__). However, this composite class is added during instantiation of the autodocumenter for consistency reasons. Therefore, ModelInspector can’t be created at instantiation time of this class because the object is still None. Hence, it is lazily created once the inspection methods are first required. At this point in time, it is guaranteed by the auto-documenter base class that object is then already correctly provided and the ModelInspector works as expected.

class PydanticModelDocumenter(*args: Any)[source]

Bases: sphinx.ext.autodoc.ClassDocumenter

Represents specialized Documenter subclass for pydantic models.

classmethod can_document_member(member: Any, membername: str, isattr: bool, parent: Any) bool[source]

Filter only pydantic models.

document_members(*args, **kwargs)[source]

Modify member options before starting to document members.

hide_config_member()[source]

Add Config to exclude_members option.

hide_validator_members()[source]

Add validator names to exclude_members.

format_signature(**kwargs) str[source]

If parameter list is to be hidden, return only empty signature.

add_content(more_content: Optional[docutils.statemachine.StringList], no_docstring: bool = False) None[source]

Delegate additional content creation.

add_collapsable_schema()[source]

Adds collapse code block containing JSON schema.

add_config_summary()[source]

Adds summary section describing the model configuration.

add_validators_summary()[source]

Adds summary section describing all validators with corresponding fields.

add_field_summary()[source]

Adds summary section describing all fields.

class PydanticSettingsDocumenter(*args: Any)[source]

Bases: sphinxcontrib.autodoc_pydantic.directives.autodocumenters.PydanticModelDocumenter

Represents specialized Documenter subclass for pydantic settings.

classmethod can_document_member(member: Any, membername: str, isattr: bool, parent: Any) bool[source]

Filter only pydantic models.

class PydanticFieldDocumenter(*args)[source]

Bases: sphinx.ext.autodoc.AttributeDocumenter

Represents specialized Documenter subclass for pydantic fields.

classmethod can_document_member(member: Any, membername: str, isattr: bool, parent: Any) bool[source]

Filter only pydantic fields.

property pydantic_field_name: str

Provide the pydantic field name which refers to the member name of the parent pydantic model.

add_directive_header(sig: str) None[source]

Delegate header options.

add_default_value_or_required()[source]

Adds default value or required marker.

add_alias()[source]

Adds alias directive option.

add_content(more_content: Optional[docutils.statemachine.StringList], no_docstring: bool = False) None[source]

Delegate additional content creation.

add_constraints()[source]

Adds section showing all defined constraints.

add_description()[source]

Adds description from schema if present.

add_validators()[source]

Add section with all validators that process this field.

class PydanticValidatorDocumenter(*args: Any)[source]

Bases: sphinx.ext.autodoc.MethodDocumenter

Represents specialized Documenter subclass for pydantic validators.

classmethod can_document_member(member: Any, membername: str, isattr: bool, parent: Any) bool[source]

Filter only pydantic validators.

format_args(**kwargs: Any) str[source]

Return empty arguments if validator should be replaced.

add_content(more_content: Optional[docutils.statemachine.StringList], no_docstring: bool = False) None[source]

Optionally show validator content.

add_field_list()[source]

Adds a field list with all fields that are validated by this validator.

class PydanticConfigClassDocumenter(*args: Any)[source]

Bases: sphinx.ext.autodoc.ClassDocumenter

Represents specialized Documenter subclass for pydantic model configuration.

classmethod can_document_member(member: Any, membername: str, isattr: bool, parent: Any) bool[source]

Filter only pydantic model configurations.

document_members(*args, **kwargs)[source]

Modify member options before starting to document members.

definition.py

This module is located at sphinxcontrib/autodoc_pydantic/directives/options/definition.py.

This module contains the autodocumenter’s option definitions.

OPTIONS_FIELD = {'__doc_disable_except__': <function option_list_like>, 'field-doc-policy': <function option_one_of_factory.<locals>.option_func>, 'field-list-validators': <function option_default_true>, 'field-show-alias': <function option_default_true>, 'field-show-constraints': <function option_default_true>, 'field-show-default': <function option_default_true>, 'field-show-required': <function option_default_true>, 'field-signature-prefix': <function unchanged>}

Represents added directive options for PydanticFieldDocumenter.

OPTIONS_VALIDATOR = {'__doc_disable_except__': <function option_list_like>, 'validator-list-fields': <function option_default_true>, 'validator-replace-signature': <function option_default_true>, 'validator-signature-prefix': <function unchanged>}

Represents added directive options for PydanticValidatorDocumenter.

OPTIONS_CONFIG = {'__doc_disable_except__': <function option_list_like>, 'config-signature-prefix': <function unchanged>, 'members': <function option_members>}

Represents added directive options for PydanticConfigDocumenter.

OPTIONS_MODEL = {'__doc_disable_except__': <function option_list_like>, 'members': <function option_members>, 'model-hide-paramlist': <function option_default_true>, 'model-show-config-member': <function option_default_true>, 'model-show-config-summary': <function option_default_true>, 'model-show-field-summary': <function option_default_true>, 'model-show-json': <function option_default_true>, 'model-show-json-error-strategy': <function option_one_of_factory.<locals>.option_func>, 'model-show-validator-members': <function option_default_true>, 'model-show-validator-summary': <function option_default_true>, 'model-signature-prefix': <function unchanged>, 'model-summary-list-order': <function option_one_of_factory.<locals>.option_func>, 'undoc-members': <function option_default_true>}

Represents added directive options for PydanticModelDocumenter.

OPTIONS_SETTINGS = {'__doc_disable_except__': <function option_list_like>, 'members': <function option_members>, 'settings-hide-paramlist': <function option_default_true>, 'settings-show-config-member': <function option_default_true>, 'settings-show-config-summary': <function option_default_true>, 'settings-show-field-summary': <function option_default_true>, 'settings-show-json': <function option_default_true>, 'settings-show-json-error-strategy': <function option_one_of_factory.<locals>.option_func>, 'settings-show-validator-members': <function option_default_true>, 'settings-show-validator-summary': <function option_default_true>, 'settings-signature-prefix': <function unchanged>, 'settings-summary-list-order': <function option_one_of_factory.<locals>.option_func>, 'undoc-members': <function option_default_true>}

Represents added directive options for PydanticSettingsDocumenter.

composites.py

This module is located at sphinxcontrib/autodoc_pydantic/directives/options/composites.py.

This module contains composite helper classes for autodoc_pydantic autodocumenters and directives. They mainly intend to encapsulate the management of directive options.

class DirectiveOptions(parent: Union[sphinx.ext.autodoc.Documenter, docutils.parsers.rst.Directive])[source]

Bases: object

Composite class providing methods to manage getting and setting configuration values from global app configuration and local directive options.

This class is tightly coupled with autodoc pydantic autodocumenters because it accesses class attributes of the parent class.

The documenter class’ option attribute is sometimes modified in order to apply autodoc pydantic’s rules (e.g. modifying :members:). Since the option attribute may be shared between documenter instances (may be a bug) in sphinx, an independent copy of the option attribute is created for every autodoc pydantic autodocumenter. This relates to #21.

add_default_options()[source]

Adds all default options.

static sanitize_configuration_option_name(name: str) str[source]

Provide full app environment configuration name for given option name while converting “-” to “_”.

Parameters

name (str) – Name of the option.

Returns

full_name – Full app environment configuration name.

Return type

str

is_available(name: str) bool[source]

Configurations may be disabled for documentation purposes. If the directive option __doc_disable_except__ exists, it contains the only available configurations.

get_app_cfg_by_name(name: str) Any[source]

Get configuration value from app environment configuration. If name does not exist, return NONE.

get_value(name: str, prefix: bool = False, force_availability: bool = False) Any[source]

Get option value for given name. First, looks for explicit directive option values (e.g. :member-order:) which have highest priority. Second, if no directive option is given, get the default option value provided via the app environment configuration.

Parameters
  • name (str) – Name of the option.

  • prefix (bool) – If True, add pyautodoc_prefix to name.

  • force_availability (bool) – It is disabled by default however some default configurations like model-summary-list-order need to be activated all the time.

is_false(name: str, prefix: bool = False) bool[source]

Get option value for given name. First, looks for explicit directive option values (e.g. :member-order:) which have highest priority. Second, if no directive option is given, get the default option value provided via the app environment configuration.

Enforces result to be either True or False.

Parameters
  • name (str) – Name of the option.

  • prefix (bool) – If True, add pyautodoc_prefix to name.

is_true(name: str, prefix: bool = False) bool[source]

Get option value for given name. First, looks for explicit directive option values (e.g. :member-order:) which have highest priority. Second, if no directive option is given, get the default option value provided via the app environment configuration.

Enforces result to be either True or False.

Parameters
  • name (str) – Name of the option.

  • prefix (bool) – If True, add pyautodoc_prefix to name.

set_default_option(name: str)[source]

Set default option value for given name from app environment configuration if an explicit directive option was not provided.

Parameters

name (str) – Name of the option.

set_members_all()[source]

Specifically sets the :members: option to ALL if activated via app environment settings and not deactivated locally by directive option.

class AutoDocOptions(*args)[source]

Bases: sphinxcontrib.autodoc_pydantic.directives.options.composites.DirectiveOptions

Composite class providing methods to handle getting and setting autodocumenter directive option values.

sanitize_configuration_option_name(name: str) str[source]

Provide full app environment configuration name for given option name.

Parameters

name (str) – Name of the option.

Returns

full_name – Full app environment configuration name.

Return type

str

add_pass_through_to_directive()[source]

Intercepts documenters add_directive_header and adds pass through.

pass_option_to_directive(name: str)[source]

Pass an autodoc option through to the generated directive.

get_filtered_member_names() Set[str][source]

Return all member names of autodocumented object which are prefiltered to exclude inherited members.

directives.py

This module is located at sphinxcontrib/autodoc_pydantic/directives/directives.py.

This module contains autodoc_pydantic’s directives.

class PydanticDirectiveBase(*args)[source]

Bases: object

Base class for pydantic directive providing common functionality.

get_signature_prefix(sig: str) Union[str, List[docutils.nodes.Text]][source]

Overwrite original signature prefix with custom pydantic ones.

class PydanticModel(*args)[source]

Bases: sphinxcontrib.autodoc_pydantic.directives.directives.PydanticDirectiveBase, sphinx.domains.python.PyClasslike

Specialized directive for pydantic models.

class PydanticSettings(*args)[source]

Bases: sphinxcontrib.autodoc_pydantic.directives.directives.PydanticDirectiveBase, sphinx.domains.python.PyClasslike

Specialized directive for pydantic settings.

class PydanticField(*args)[source]

Bases: sphinxcontrib.autodoc_pydantic.directives.directives.PydanticDirectiveBase, sphinx.domains.python.PyAttribute

Specialized directive for pydantic fields.

add_required(signode: sphinx.addnodes.desc_signature)[source]

Add [Required] if directive option required is set.

add_alias(signode: sphinx.addnodes.desc_signature)[source]

Add alias to signature if alias is provided via directive option.

handle_signature(sig: str, signode: sphinx.addnodes.desc_signature) Tuple[str, str][source]

Optionally call add alias method.

class PydanticValidator(*args)[source]

Bases: sphinxcontrib.autodoc_pydantic.directives.directives.PydanticDirectiveBase, sphinx.domains.python.PyMethod

Specialized directive for pydantic validators.

replace_return_node(signode: sphinx.addnodes.desc_signature)[source]

Replaces the return node with references to validated fields.

handle_signature(sig: str, signode: sphinx.addnodes.desc_signature) Tuple[str, str][source]

Optionally call replace return node method.

class PydanticConfigClass(*args)[source]

Bases: sphinxcontrib.autodoc_pydantic.directives.directives.PydanticDirectiveBase, sphinx.domains.python.PyClasslike

Specialized directive for pydantic config class.