sphinx
sphinx copied to clipboard
Add __init__ parameter docs to attrs classes from attribute docstring
Problem
When I generate documentation using sphinx.ext.autodoc for my attrs classes' __init__ (using :special-members: __init__), the parameters for __init__ aren't documented.
Solution
I'd like autodoc to populate the documentation for __init__'s parameters from the documented attributes, if any and if not already specified. Up to the implementer whether a check for __attrs_attrs__ or __dataclass_fields__ is also performed.
Minimal reproducible example (click to expand)
docs/src/conf.py
extensions = ["sphinx.ext.autodoc"]
autodoc_class_signature = "separated"
docs/src/index.rst
Spam
====
.. automodule:: spam
:members:
:special-members: __init__
spam.py
import attr
@attr.s(auto_attribs=True, init=True, eq=False)
class Spam:
"""Test attrs class."""
eggs: str = "foo"
"""Possibly flipped."""
Run:
$ pip install sphinx attrs
$ PYTHONPATH=. sphinx-build docs/src docs/build
Desired
class spam.Spam
Test attrs class.
__init__(eggs: str = 'foo') → None
Method generated by attrs for class Spam.
Parameters:
eggs – possibly flipped
eggs: str
Possibly flipped.
Actual
class spam.Spam
Test attrs class.
__init__(eggs: str = 'foo') → None
Method generated by attrs for class Spam.
eggs: str
Possibly flipped.
Note any solution needs to also work with autodoc_typehints = "description" (and "both") and autoclass_content = "class" (and "both").
Alternatives
- I could write my own
__init__with a docstring, but that defeats the purpose of usingattrs. - I could unset
autodoc_class_signatureand remove:special-members: __init__, but that makes it difficult to distinguish class/instance attributes from__init__parameters. - I could extend
attr.sto add__init__docstring using theattr.ib-annotated class attribute's docstring, but that requires Sphinx-style parsing of those docstrings (which Python doesn't provide by default).