【问题标题】:How to specify multiple return types in a function docstring in Python?如何在 Python 的函数文档字符串中指定多个返回类型?
【发布时间】:2019-02-06 11:30:54
【问题描述】:

我知道用于为 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

但是,我想知道同时提供类型和描述的最佳方式是什么,以便 Napoleon 支持它原生并且也易于阅读文档。

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

    Returns:
      int/str: integer if a > b and a string otherwise

【问题讨论】:

标签: python python-sphinx return-type docstring sphinx-napoleon


【解决方案1】:

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

from typing import Type, Dict, Optional

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

Here你可以找到更多信息

【讨论】:

  • 感谢分享这个,但我正在寻找一种方法来使用将由 sphinx 读取的文档字符串来处理这个问题。
  • 可选获取单个参数,例如浮动,表示浮动或无。 Python 3.10之后,这个也可以写成float |没有。 (可选[浮动] = 浮动 | 无)。在这里你需要联合。
【解决方案2】:

如上所述,但使用 Union 代替。 (在不确定是否返回数据类型时使用Optional,Union用于确定返回两种数据类型之一的情况。)

from typing import Type, Dict, Union

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

【讨论】:

  • 上例中应该是Union吧?
  • 您导入了Union,但使用了未导入的Optional。此代码会导致错误请更正
猜你喜欢
  • 2018-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-23
  • 2020-01-28
  • 1970-01-01
  • 2021-10-15
相关资源
最近更新 更多