How to automatically add parameter types in sphinx documentation

孤人 提交于 2020-01-23 05:42:05

问题


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:

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:


回答1:


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.



来源:https://stackoverflow.com/questions/49540656/how-to-automatically-add-parameter-types-in-sphinx-documentation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!