sphinx icon indicating copy to clipboard operation
sphinx copied to clipboard

Add __init__ parameter docs to attrs classes from attribute docstring

Open EpicWink opened this issue 3 years ago • 0 comments

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 using attrs.
  • I could unset autodoc_class_signature and remove :special-members: __init__, but that makes it difficult to distinguish class/instance attributes from __init__ parameters.
  • I could extend attr.s to add __init__ docstring using the attr.ib-annotated class attribute's docstring, but that requires Sphinx-style parsing of those docstrings (which Python doesn't provide by default).

EpicWink avatar Jul 19 '22 09:07 EpicWink