【问题标题】:How to automatically add parameter types in sphinx documentation如何在 sphinx 文档中自动添加参数类型
【发布时间】:2018-09-07 12:02:33
【问题描述】:

我目前正在尝试使用 Sphinx 实现自动文档创建(使用扩展 sphinx-apidoc 和拿破仑)。这很好用,但如果类型提示(PEP484 约定)自动添加到参数列表中会更好。

我想知道这是否可能。

更具体地说:(来自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.

    """

呈现如下:

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

手动类型添加示例:

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.

    """

呈现为:

【问题讨论】:

  • 这就是我们所说的狮身人面像——如果答案不是“你必须使用这个猴子补丁”,我会吃一顶帽子。
  • 这个问题似乎相关:github.com/sphinx-doc/sphinx/issues/2738
  • 该问题的最后一条评论正是我的意思。同时:有人知道解决方法吗?

标签: python python-sphinx type-hinting sphinx-napoleon sphinx-apidoc


【解决方案1】:

您现在可以使用sphinx-autodoc-typehints 扩展名。当您在上面的前一个示例中编写时,它会自动将类型添加到 sphinx 文档字符串中。

要安装,只需:

$ pip install sphinx-autodoc-typehints

'sphinx_autodoc_typehints' 添加到conf.py 中的extensions 列表之后 'sphinx.ext.napoleon',并确保您还将napoleon_use_param = True 添加到conf.py

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-15
    • 2021-11-16
    • 1970-01-01
    • 2011-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多