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