如何在sphinx文档中自动添加参数类型

13

我目前正在尝试使用Sphinx(使用扩展程序sphinx-apidoc和napoleon)实现自动文档创建。这个方法非常有效,但如果能够自动添加参数列表中的类型提示(PEP484约定),那就更好了。

我想知道这是否可能。

更具体地说: (来自napoleon示例

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.

    """

这将呈现如下:

输入图像描述

参数列表包含所有参数,但不附加类型。可以手动添加它们,但这可能会在决定更改签名时引入未来的问题。

手动添加类型的示例:

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.

    """

该段代码将呈现为:

enter image description here


3
我们正在谈论Sphinx - 如果答案不是“你必须使用这个monkeypatch”,那我就吃帽子。 - Aran-Fey
1
这个问题似乎与以下相关:https://github.com/sphinx-doc/sphinx/issues/2738 - mzjn
那个问题中的最后一条评论正是我想表达的。同时,有人知道解决方法吗? - Matthijs
1个回答

14

现在您可以使用sphinx-autodoc-typehints扩展程序。当您按照上面的示例编写时,它会自动将类型添加到sphinx docstrings中。

要安装,请执行以下操作:

$ pip install sphinx-autodoc-typehints
conf.py文件的'sphinx.ext.napoleon'之后,将'sphinx_autodoc_typehints'添加到extensions列表中,并确保还将napoleon_use_param = True添加到conf.py

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接