Skip to content

Add typehint support for sphinx.ext.autodoc #1

@sgraaf

Description

@sgraaf

The idea here is to define type hints only in the class / function signature and leave them out of the docstring.

I first noticed that structlog has a nice API reference with type annotations, without including them in the docstrings (only in the signature). For this, they use the (undocumented ?!) sphinx.ext.autodoc.typehints Sphinx extension.

Alternatives exist, like sphinx-autodoc-typehints, which gives the following example:

This allows you to use type hints in a very natural fashion, allowing you to migrate from this:

def format_unit(value, unit):
    """
    Formats the given value as a human readable string using the given units.

    :param float|int value: a numeric value
    :param str unit: the unit for the value (kg, m, etc.)
    :rtype: str
    """
    return f"{value} {unit}"

to this:

from typing import Union


def format_unit(value: Union[float, int], unit: str) -> str:
    """
    Formats the given value as a human readable string using the given units.

    :param value: a numeric value
    :param unit: the unit for the value (kg, m, etc.)
    """
    return f"{value} {unit}"

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions