astral-sh / ruff

An extremely fast Python linter and code formatter, written in Rust.
https://docs.astral.sh/ruff
MIT License
30.15k stars 982 forks source link

Add support for attribute docstrings #10347

Open tibdex opened 5 months ago

tibdex commented 5 months ago

The goal of this issue is to get Ruff to lint and format attribute docstrings as already done for class/method/function docstrings.

PEP 224 is about attribute docstrings. It was rejected but its proposed syntax (where a triple quote string can be placed under a class attribute to document it) has become a de facto standard:

For example, with this code:

from dataclasses import dataclass

@dataclass
class Demo:
    """Demo."""

    value: int
    """The value."""

Sphinx outputs the expected HTML:

Screenshot 2024-03-11 at 17 29 48

and shpinx.ext.doctest would even detect interactive Python sessions in value's docstring and check them.

VS Code also shows the attribute docstring on hover:

Screenshot 2024-03-11 at 17 33 38

On the other hand, with this code trying to document the attribute in a Google style docstring:

from dataclasses import dataclass

@dataclass
class Demo:
    """Demo.

    Attributes:
        value: The value.
    """

    value: int

Sphinx, even with sphinx.ext.napoleon correctly configured, duplicates the attribute:

Screenshot 2024-03-11 at 17 29 03

and VS Code does not show the docstring on hover:

Screenshot 2024-03-11 at 17 33 59

Would you consider detecting this syntax as attribute docstrings and handling them like the other docstrings (e.g. formatting code examples in them)?

[!NOTE] PEP 727 is a draft suggesting to document attributes like this:

from typing import Annotated, Doc

class Demo:
    value: Annotated[int, Doc("The value.")]

typing-extensions already provides it but Sphinx and VS Code do not support it.

charliermarsh commented 5 months ago

I'm generally supportive of this.

dhruvmanila commented 2 months ago

Ruff can now detect this via https://github.com/astral-sh/ruff/pull/11315 although it's currently not being used anywhere (linter or formatter).