Python 文档字符串中是否有结构化的方法来引用函数参数标签?

Is there a structured way to reference function parameter labels in Python docstring?

我正在使用工具 pydoc 自动生成文档。给定函数:

def sum(a, b):
  """Returns the sum of a and b."""
  return a + b

我很好奇是否有结构化的方式使用markdown来突出对函数参数标签的引用?例如:

"""Returns the sum of 'a' and 'b'."""
"""Returns the sum of `a` and `b."""
"""Returns the sum of *a* and *b*."""
"""Returns the sum of **a** and **b**."""

类似于这个问题Referencing parameters in a Python docstring,它是关于使用 Sphinx 而不是 pydoc。

另请注意,我对引用函数参数的标签(而不是类型)很好奇。

Pydoc 不支持 markdown。

文档字符串中的格式仅限于 recognising PEP and RFC references, self. attribute references and links for existing names (for other classes, methods, and functions) when rendering to HTML,因此在该模式下,一些名称已经被标记。但是,这不会扩展到参数名称。

Pydoc 确实使用 inspect.signature() output as the basis for formatting the function, so if you make sure you have informative type hints,那么您至少会记录参数的类型和 return 值。

所以一个(相当人为的)定义使用通用 TypeVar 定义而不是坚持 float,例如:

from typing import TypeVar

Number = TypeVar('Number', int, float)

def sum(a: Number, b: Number) -> Number:
    """Produce the sum of the two numbers, a and b"""
    return a + b

出现在 pydoc 中

sum(a: ~Number, b: ~Number) -> ~Number
    Produce the sum of the two numbers, a and b