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

标签 python python-sphinx return-type docstring 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.

    """

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

下面是一个例子。 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}

有一个 example 显示两种不同的可能返回类型:
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

但是,我想知道提供这两种类型和描述的最佳方法是什么,以便拿破仑支持它 native ,并且也很容易阅读文档。

使用 int/str: %description% 是处理多个返回类型的唯一方法吗?
    Returns:
      int/str: integer if a > b and a string otherwise

最佳答案

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

from typing import Type, Dict, Optional

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

Here 你可以找到更多信息

关于python - 如何在 Python 的函数文档字符串中指定多个返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54552649/

相关文章:

python - 有人可以解释一下这些 Python 字符串格式化程序吗

python - 使用 python 从文本文件中仅获取第一行的正则表达式代码

python - 如何删除xlwings中的列?

c - 故意返回无效值或类型

python - TensorFlow 2.0 如何从 tf.keras.layers 层获取可训练变量,如 Conv2D 或 Dense

python-sphinx - 如何使用 ReadTheDocs 或 Sphinx 托管私有(private)文档

python - 自托管 Sphinx 文档中的多个版本

python - 指示 Sphinx 使用特定版本的 Python

java - 方法可以返回抽象类类型吗?

polymorphism - 类 C 语言中的返回类型多态性