pythonpython-sphinxtype-hintingautodocsphinx-napoleon

Skipping type hints in documentation


Let's consider the following function:

def f(x: int, y: int) -> int:
    """Get sum of two integers.

    Parameters
    ----------
    x : int
        first integer
    y : int
        second integer

    Returns
    -------
    int
        sum of the provided integers
    """
    return x + y

While documenting with Sphinx (v3.2.1), the documentation is generated in the following form:

enter image description here

However, I don't see a point to show type hints as in f(x: int, y:int) -> int in the heading of function documentation, and also in the Parameters section. In this case, it doesn't really matter, but it makes it very unreadable with functions with 4-5 arguments. Is there a way to skip the type hint? Like, I'll prefer if the heading is just f or f(x, y).

I expected this has something to do with add_function_parentheses, but setting it as False in conf.py didn't have any effect that I've noticed.

A related issue is that if type hint is long, may be like typing.Union with multiple long descriptions, where I do not want to use typing.Any, i often write those in the docstring across multiple lines, adhering to maximum line limit. In those cases, the Parameters section shows that the type is what is in the first line, and next lines are just descriptions. I'm not attaching an example of this issue, as I am not sure whether these are same or not. If they are, please let me know and I'll update with an example.


Solution

  • There is an option autodoc_typehints for sphinx.ext.autodoc. This has 3 options: none, description and signature (default). Using either of none or description will hide type hints in the header line. The only difference I can find in between these two is that if docstrings do not contain type suggestions, description will still show them in the documentation collecting from type hints.

    To use this, following changes are required in conf.py:

    1. add sphinx.ext.autodoc in extensions (if not done already)
    2. set autodoc_typehints = "none"