Documenting class attributes with type annotations

4.7k Views Asked by At

I want to autogenerate documentation to my code from docstrings. I have some basic class meant to store some data:

class DataHolder:
    """
    Class to hold some data

    Attributes:
        batch: Run without GUI
        debug (bool): Show debug messages
    """
    batch: bool = False
    debug: bool = False
    name: str = 'default'
    """Object name"""
    version: int = 0
    """int: Object version"""

My rst file:

DataHolder
==========

.. autoclass:: data_holder.DataHolder
   :members:

I have documented each attribute in a different way to show the difference, here is the output:
enter image description here

It seems like Sphinx cannot connect the Attributes section with the real attributes, that's why it cannot display their default value.

The final output I would like to achieve is the outcome as for the version field with the docstring defined as for batch. I want to display the attribute name with default value and type, but taken from type annotations. Looks like Sphinx is ignoring the type annotations in this case.

My sphinx extensions:

extensions = [
    'sphinx.ext.viewcode',
    'sphinx.ext.autodoc',
    'sphinxcontrib.napoleon',
]

What can I do to achieve such behavior? I can't find any good examples for such use case.

2

There are 2 best solutions below

0
On

I do not think you can put an Attribute section inside of your docstring to get your desired results.

I tried giving each attribute a doc comment and specified the type and desired comment.

class DataHolder:
"""
Class to hold some data

Each attribute needs its own doc comment with its type
"""

#: bool: Run without Gui
batch = False

#: bool: Show debug messages
debug = False

#: str: Object Name
name = 'default'

#: int: Object Version
version = 0

This gives the following output and a nice Type description of each output.

Take a look here:

Please take a look here!

1
On
class DataHolder:
    """
    Class to hold some data

    Attributes:
        batch: Run without GUI
        debug (bool): Show debug messages
        name: Object name
        version: Object version
    """
    batch: bool = False
    debug: bool = False
    name: str = 'default'
    version: int = 0
    # INLINE COMMENT for ONE line
    """
    DocString as inline-comment I havent seen that yet.
    """