tox-dev / sphinx-autodoc-typehints

Type hints support for the Sphinx autodoc extension
MIT License
550 stars 103 forks source link

support pep 593 typing.Annotated to avoid repeating `:param {arg}:` for each arg #149

Open graingert opened 4 years ago

graingert commented 4 years ago

https://www.python.org/dev/peps/pep-0593/

# sphinx_autodoc_typehints.py

from typing import Annotated, TypeVar, Generic

T = TypeVar('T')
U = TypeVar('U')

class Doc(Generic[U]):
    ...

Doc = Annotated[T, Doc[U]]

this would allow use as:

from typing import Union

from sphinx_autodoc_typehints import Doc

def format_unit(
    value: Doc[Union[float, int], "a numeric value"],
    unit: Doc[str, "the unit for the value (kg, m, etc.)"],
) -> Doc[str, "a human readable string"]:
    """
    Formats the given value as a human readable string using the given units.
    """
    return '{} {}'.format(value, unit)
JustAnotherArchivist commented 2 years ago

I'd love to put the descriptions in annotations as well! Your proposed syntax has one major disadvantage though: it essentially ruins the flexibility of annotations. I'm not sure Annotated is actually used anywhere so far, but consider the case where you'd want to also use the hypothetical ValueRange annotation shown in the PEP's examples.

Something like the following would avoid this and remain fully compatible with any other current or future use of annotations:

from typing import Annotated, Union

from sphinx_autodoc_typehints import Doc

def format_unit(
    value: Annotated[Union[float, int], Doc("a numeric value")],
    unit: Annotated[str, Doc("the unit for the value (kg, m, etc.)")],
) -> Annotated[str, Doc("a human readable string")]:
    """
    Formats the given value as a human readable string using the given units.
    """
    return '{} {}'.format(value, unit)

Of course, there could be a shorthand for Annotated[T, Doc(str)] for convenience when no other annotations are necessary to avoid the bulkier syntax for the (for now) presumably most common case.

gaborbernat commented 2 years ago

A PR for this would we welcome.