如何在Python中的函数文档字符串中指定多个返回类型?

Ale*_*kov 12 python docstring return-type python-sphinx sphinx-napoleon

我知道用于构建 Google 风格的文档字符串的语法,例如:

def function_with_types_in_docstring(param1, param2):
    """Example function with types documented in the docstring.

    `PEP 484`_ type annotations are supported. If attribute, parameter, and
    return types are annotated according to `PEP 484`_, they do not need to be
    included in the docstring:

    Args:
        param1 (int): The first parameter.
        param2 (str): The second parameter.

    Returns:
        bool: The return value. True for success, False otherwise.

    """
Run Code Online (Sandbox Code Playgroud)

但是,如果我有一个函数可以根据执行的代码分支返回多种类型怎么办?记录这一点的正确方法是什么?

下面是一个例子。该部分应该放入什么Returns

def foo(x, y):
    """Dummy function.

    Args:
        x (int): integer
        y (int): integer

    Returns:
        list/dict: either list or a dict depending on...

    """
    if x > y:
        return [1, 2, 3]
    if x < y:
        return {1:2}
Run Code Online (Sandbox Code Playgroud)

有一个示例显示两种不同的可能返回类型:

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
Run Code Online (Sandbox Code Playgroud)

但是,我想知道提供两种类型和描述的最佳方式是什么,以便拿破仑能够原生支持它,并且也可以轻松阅读文档。

使用是int/str: %description%处理多种返回类型的唯一方法吗?

    Returns:
      int/str: integer if a > b and a string otherwise
Run Code Online (Sandbox Code Playgroud)

jud*_*ane 2

如果你想使用注释来根据函数结果指定不同类型的返回类型,你可以这样做:

from typing import Type, Dict, Optional

def function(self) -> Optional[dict, str]:
    if self.result:
        return self.result
    else:
        return "Empty result"
Run Code Online (Sandbox Code Playgroud)

在这里您可以找到更多信息

  • 感谢您分享这一点,但我正在寻找一种使用文档字符串来处理此问题的方法,该文档字符串将由 sphinx 读取。 (6认同)