13

I am currently trying to implement automatic documentation creation with Sphinx (using the extensions sphinx-apidoc and napoleon). This works quite well, but it would be even better if the typehints (PEP484 convention) are added automatically to the params list.

I was wondering whether this is possible.

More concretely: (from the napoleon example)

def function_with_pep484_type_annotations(param1: int, param2: str) -> bool:
    """Example function with PEP 484 type annotations.

    Args:
        param1: The first parameter.
        param2: The second parameter.

    Returns:
        The return value. True for success, False otherwise.

    """

This renders as follows:

enter image description here

The parameters list has all the parameters, but does not attach the types. It is possible to add them manually, but this might introduce future problems when is decided to change the signature.

Example with manual type addition:

def function_with_pep484_type_annotations(param1: int, param2: str) -> bool:
    """Example function with PEP 484 type annotations.

    Args:
        param1 (int): The first parameter.
        param2 (str): The second parameter.

    Returns:
        The return value. True for success, False otherwise.

    """

which renders as:

enter image description here

3
  • 3
    This is sphinx we're talking about - if the answer isn't "You have to use this monkeypatch", I'll eat a hat. Commented Mar 28, 2018 at 17:39
  • 1
    This issue seems related: github.com/sphinx-doc/sphinx/issues/2738 Commented Mar 28, 2018 at 17:55
  • The last comment in that issue is exactly what i mean. In the meantime: does some-one know a workaround? Commented Mar 28, 2018 at 18:11

1 Answer 1

16

You can now use the sphinx-autodoc-typehints extension. It will automatically add the types to the sphinx docstrings when you write in the former example above.

To install, just do:

$ pip install sphinx-autodoc-typehints

Add 'sphinx_autodoc_typehints' to the extensions list in conf.py after 'sphinx.ext.napoleon', and make sure you also add napoleon_use_param = True to conf.py.

Sign up to request clarification or add additional context in comments.

1 Comment

I think the project link should be github.com/tox-dev/sphinx-autodoc-typehints

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.