如何使用类型提示指定多个 return 类型

How to specify multiple return types using type-hints

我在 python 中有一个函数可以 return 或 boollist。有没有办法使用类型提示指定 return 类型?

例如,这是正确的做法吗?

def foo(id) -> list or bool:
    ...

来自documentation

class typing.Union

Union type; Union[X, Y] means either X or Y.

因此表示多个 return 数据类型的正确方法是

from typing import Union


def foo(client_id: str) -> Union[list,bool]

但请注意,输入不是强制的。 Python 继续保持动态类型语言。注释语法的开发是为了在代码发布到生产环境之前的开发过程中提供帮助。正如 PEP 484 所述,“在运行时不会进行类型检查。”

>>> def foo(a:str) -> list:
...     return("Works")
... 
>>> foo(1)
'Works'

如您所见,我正在传递一个 int 值并 returning 一个 str。但是 __annotations__ 将被设置为相应的值。

>>> foo.__annotations__ 
{'return': <class 'list'>, 'a': <class 'str'>}

请通过 PEP 483 for more about Type hints. Also see ?

请注意,这仅适用于 Python 3.5 及更高版本。 PEP 484.

中明确提到了这一点

从Python 3.10 开始,有一种新的方式来表示这个联盟。见 Union Type:

A union object holds the value of the | (bitwise or) operation on multiple type objects. These types are intended primarily for type annotations. The union type expression enables cleaner type hinting syntax compared to typing.Union.

正如我们所看到的,这与之前版本中的typing.Union完全相同。我们之前的示例可以修改为使用此表示法:

def foo(client_id: str) -> list | bool:

语句 def foo(client_id: str) -> list or bool: 计算时等同于 def foo(client_id: str) -> list: 因此不会按照您的意愿行事。

描述“A 或 B”类型提示的原生方式是 Union(感谢 Bhargav Rao):

def foo(client_id: str) -> Union[list, bool]:

或者,starting with Python 3.10 and beyond,使用 | 运算符:

def foo(client_id: str) -> list | bool:

我不想成为“你为什么要这样做”的人,但也许拥有 2 return 类型并不是你想要的:

如果您想 return 一个布尔值来指示某种类型的特殊错误情况,请考虑改用异常。如果你想 return 一个 bool 作为一些特殊值,也许一个空列表会是一个很好的表示。 您还可以指出 None 可以 return 编辑 Optional[list]

万一有人在这里搜索“如何指定多个 return 值的类型?”,请使用 Tuple[type_value1, ..., type_valueN]

from typing import Tuple

def f() -> Tuple[dict, str]:
    a = {1: 2}
    b = "hello"
    return a, b

更多信息:

Python 3.10(使用 |):接受单个参数的函数示例,该参数可以是 intstr 和 returns 或者 intstr:

def func(arg: int | str) -> int | str:
              ^^^^^^^^^     ^^^^^^^^^ 
             type of arg   return type

Python 3.5 - 3.9(使用typing.Union):

from typing import Union
def func(arg: Union[int, str]) -> Union[int, str]:
              ^^^^^^^^^^^^^^^     ^^^^^^^^^^^^^^^ 
                type of arg         return type

对于 X | None 的特殊情况,您可以使用

在基础 Python 中简单地做:

def foo(x: (list, str)):
    pass