[英]How to specify multiple return types in a function docstring in Python?
我知道用于为 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}
有一个示例显示了两种不同的可能返回类型:
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
但是,我想知道提供这两种类型和描述的最佳方法是什么,以便拿破仑支持它本机并且也很容易阅读文档。
使用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"
在这里你可以找到更多信息
如上所述,但使用 Union 代替。 (如果不确定是否返回数据类型,则使用可选,Union 用于确定返回两种数据类型之一的情况。)
from typing import Type, Dict, Union
def function(self) -> Optional[dict, str]:
if self.result:
return self.result
else:
return "Empty result"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.