Reputation: 510
Given the following function in a module called mymodule
that I want to document using Sphinx with autodoc
:
from typing import Union
from collections.abc import Iterable
from numpy.typing import ArrayLike
def foo(a: Union[str, int], b: Iterable, c: ArrayLike) -> None:
"""Do something useful."""
pass
In the source, the function's signature is quite readable. However, in the documentation generated by autodoc
the signature is displayed as
mymodule.foo(a: Union[str, int], b: collections.abc.Iterable, c: Union[int, float, complex, str, bytes, numpy.generic, Sequence[Union[int, float, complex, str, bytes, numpy.generic]], Sequence[Sequence[Any]], numpy.typing._array_like._SupportsArray]) → None
which is just unreadable. The classes stemming from the typing
module are displayed in a short form (Union
, Sequence
, Any
), but for the abstract base class Iterable
a unique identifier is generated (collections.abc.Iterable
) and ArrayLike
is even "unpacked" (Union[int, float, complex, str, bytes, numpy.generic, Sequence[Union[int, float, complex, str, bytes, numpy.generic]], Sequence[Sequence[Any]], numpy.typing._array_like._SupportsArray]
).
How can I configure Sphinx so that the function's signature is displayed in a readable way in the documentation, e.g. as in the source code?
Upvotes: 6
Views: 2018
Reputation: 510
After some more digging I found that the autodoc_type_aliases
option can be used to achieve this. In order to make it work, you have to say
from __future__ import annotations
at the start of the module you are documenting. (This activates postponed evaluation of annotations as outlined in PEP563 which will become the standard in Python 3.10.)
You can then tell Sphinx how to print the annotations in your conf.py
file.
autodoc_type_aliases = {
'Iterable': 'Iterable',
'ArrayLike': 'ArrayLike',
}
(The key of each entry is the type hint as written in the source, the value is how it will be written in the generated documentation.)
Upvotes: 10
Reputation: 136177
When I googled this question, I was looking for autodoc_typehints_format and python_use_unqualified_type_names (sphinx>=4.0 is required
):
# put this in your docs/conf.py for Sphinx
autodoc_typehints_format = 'short'
python_use_unqualified_type_names = True
Upvotes: 4