sphinx-doc / sphinx

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

`napoleon_attr_annotations` doesn't work for class instance attributes #10527

Open Skylake-dev opened 2 years ago

Skylake-dev commented 2 years ago

Describe the bug

I am using the napoleon extension for my google-style docstrings. Since the code already has type annotations i do not want to repeat those in the docstring. I found that napoleon can be configured with napoleon_attr_annotations The documentation says: True to allow using PEP 526 attributes annotations in classes. If an attribute is documented in the docstring without a type and has an annotation in the class body, that type is used.

However, the result is not as i would expect because type annotation are missing from the documentation.

How to Reproduce

$ git clone https://github.com/Skylake-dev/mal.py
$ cd mal.py
$ pip install -r requirements.txt
$ cd docs
$ make html
$ # open _build/html/index and check any class that has attribute annotated

Expected behavior

I would expect the class instance attributes to be annotated with types since in the PEP 526 it is stated that they can be annotated in the __init__ method and they show a code sample

from typing import Generic, TypeVar
T = TypeVar('T')

class Box(Generic[T]):
    def __init__(self, content):
        self.content: T = content

Your project

https://github.com/Skylake-dev/mal.py

Screenshots

code sample of one of the classes

class Genre():
    """Represents a specific genre. It has two read only properties that are the
    id and the name of the genre.

    Attributes:
        id: The id of the genre.
        name: The name of the genre.
    """

    def __init__(self, data: GenericPayload) -> None:
        self.id: int = data['id']
        self.name: str = data['name']

relevant part of the conf.py file

extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.napoleon',
    'sphinx.ext.autosummary',
    'sphinx.ext.intersphinx'
]

autosummary_generate = True
autodoc_default_options = {
    'inherited-members': True
}
autodoc_typehints_format = 'short'
autodoc_member_order = 'bysource'
autodoc_preserve_defaults = True
napoleon_attr_annotations = True    # <-- this should enable PEP526 annotations

readthedocs.io render of the documentation, same result as in local, type annotation are not present read the docs

OS

Windows 10

Python version

3.9.7

Sphinx version

4.5.0

Sphinx extensions

sphinx.ext.autodoc, sphinx.ext.napoleon, sphinx.ext.autosummary, sphinx.ext.intersphinx

Extra tools

No response

Additional context

No response

mwichmann commented 2 years ago

Was just hunting around for this as well. The topic gets a fair bit of discussion in #2115.