46

有时 Python 中的函数可能会接受灵活类型的参数。或者它可能返回一个灵活类型的值。现在我不记得这样的函数的一个很好的例子了,因此我用下面的玩具例子来演示这样的函数可能是什么样子。

我想知道如何使用 Sphinx 文档符号为此类函数编写文档字符串。在下面的示例中,参数可能是strint。同样,它可能会返回strint

我已经给出了一个示例文档字符串(包括默认的 Sphinx 表示法以及 Sphinx 的拿破仑扩展所理解的 Google 表示法)。我不知道这是否是记录灵活类型的正确方法。

狮身人面像默认符号:

def add(a, b):
    """Add numbers or concatenate strings.

    :param int/str a: String or integer to be added
    :param int/str b: String or integer to be added
    :return: Result
    :rtype: int/str
    """
    pass

狮身人面像拿破仑谷歌符号:

def add2(a, b):
    """Add numbers or concatenate strings.

    Args:
      a (int/str): String or integer to be added
      b (int/str): String or integer to be added

    Returns:
      int/str: Result
    """
    pass

在要由 Sphinx 处理的文档字符串中表达参数或返回值的多种类型的正确方法是什么?

4

1 回答 1

52

Python 3.5Union类型提示

https://docs.python.org/3/library/typing.html#typing.Union

对于 Python 2,我建议使用与 Python 3 模块完全相同的语法,它将:

  • 稍后使移植更容易,并且可能是自动化的
  • 指定一种独特的、定义明确的规范方式来做事

例子:

def f(int_or_float):
    """
    :param int_or_float: Description of the parameter
    :type int_or_float: Union[int, float]
    :rtype: float
    """
    return int_or_float + 1.0

然后当你有 3.5 时,你将只写:

from typing import Union

def f(int_or_float : Union[int, float]) -> float:
    """
    :param int_or_float: Description of the parameter
    """
    return int_or_float + 1.0

我认为它已经支持文档生成,但我还没有测试过:https ://github.com/sphinx-doc/sphinx/issues/1968

于 2016-11-25T09:45:30.370 回答