19

I am generating a HTML documentation of a Python 3 module automatically from its reStructuredText docstrings of its functions by using Sphinx (make HTML). The generated HTML documentation looks fine so far, but the parameter types of the function signatures, which are given in the source code as PEP484 type hints aren't shown correctly.

E.g. this is some example output from the Sphinx-generated HTML doc of one of my functions:

static parse_from_file(filename: str) → list
    Parses stuff from a text file.

    Parameters:  filename – the filepath of a textfile to be parsed
    Returns:     list of parsed elements

This is what I would expect it to look like:

static parse_from_file(filename)
    Parses stuff from a text file.

    Parameters:  filename (str) – the filepath of a textfile to be parsed
    Returns:     list of parsed elements
    Return type: list

This is how the Python code actually looks like:

def parse_from_file(filename: str) -> list:
    """Parses stuff from a text file.

    :param filename: the filepath of a textfile to be parsed
    :returns: list of parsed elements
    """
    return []

How can I make Sphinx show the Python 3 type hints correctly?

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Johann Hagerer
  • 1,048
  • 2
  • 10
  • 28
  • 1
    Putting the types in the docstring isn't an option? `:param str filename: ...` and `:rtype: list` for the return type... – Bakuriu Oct 19 '16 at 06:54
  • 6
    That would make it redundant and people in our project won't think about changing the types two times. Besides, it looks like Sphinx supports PEP484 type hints: https://github.com/sphinx-doc/sphinx/issues/1968 – Johann Hagerer Oct 19 '16 at 07:19

2 Answers2

19

I tackled it on my own by using the sphinx-autodoc-typehints extension.

Johann Hagerer
  • 1,048
  • 2
  • 10
  • 28
  • Might be worth noting that this extension currently doesn't work for classes without an `__init__()` in Python 3.6 - see [my ticket](https://github.com/agronholm/sphinx-autodoc-typehints/issues/12). –  Jan 03 '17 at 13:57
17

There is autodoc_typehints variable. Since version 3.0 you can set it to 'description' which shows typehints as content of function or method and removes them from signature.

So just add this line into your conf.py:

autodoc_typehints = "description"
Břetislav Hájek
  • 3,056
  • 2
  • 15
  • 17