sphinx-doc / sphinx

The Sphinx documentation generator
https://www.sphinx-doc.org/
Other
6.26k stars 2.04k forks source link

pydantic model_post_init is rendered in documentation #12512

Open dibellaa opened 3 weeks ago

dibellaa commented 3 weeks ago

Describe the bug

I have a project that uses Pydantic. I recently updated it to v2 and I still use sphinx==7.2.6. I noticed in the autogenerated source documentation, that models have the method model_post_init. This method is not override in my project and it comes directly from Pydantic BaseModel.

image

How to Reproduce

I cannot share source since it is covered by copyright.

Environment Information

Platform:              darwin; (macOS-14.5-arm64-arm-64bit)
Python version:        3.11.6 (main, Mar 21 2024, 12:22:14) [Clang 15.0.0 (clang-1500.3.9.4)])
Python implementation: CPython
Sphinx version:        7.2.6
Docutils version:      0.20.1
Jinja2 version:        3.0.3
Pygments version:      2.18.0

Sphinx extensions

extensions = [
    'sphinx.ext.napoleon',
    'sphinxcontrib.autodoc_pydantic',
    'sphinx.ext.intersphinx',
    'myst_parser',
]

Additional context

No response

electric-coder commented 3 weeks ago

Surest workaround is to exclude the said method in autodoc_default_options adding something like this in your conf.py:

autodoc_default_options = {
    'exclude-members': 'model_post_init'
}

The bug you report seems uncommon and particular to the extensions you're using:

extensions = [
    'sphinx.ext.napoleon',
    'sphinxcontrib.autodoc_pydantic',
    'sphinx.ext.intersphinx',
    'myst_parser',
]

The likely culprit isn't Sphinx core but the autodoc_pydantic extension since they say on their main page:

Perfect, let’s go. But wait, sphinx’ autodoc does not integrate too well with pydantic models 😕.

I think you should report this on their repo before you report it here.


This bug is reminiscent of some dataclass bugs since that type also has a __post_init__(). However since pydantic models aren't part of the standard library it's a safer bet to ask the extension authors to make a diagnoses.