从文档中 -联合型 https://docs.python.org/3/library/stdtypes.html#types-union:
联合对象保存的值|
(按位或)多个运算类型对象 https://docs.python.org/3/library/stdtypes.html#bltin-type-objects。这些类型主要用于类型注释 https://docs.python.org/3/glossary.html#term-annotation。与相比,联合类型表达式可以实现更清晰的类型提示语法typing.Union https://docs.python.org/3/library/typing.html#typing.Union.
这种使用|
在 Python 3.10 中添加。因此,表示多个返回数据类型的正确方法是:
def foo(client_id: str) -> list | bool:
对于早期版本,请使用typing.Union https://docs.python.org/3/library/typing.html#typing.Union:
from typing import Union
def foo(client_id: str) -> Union[list, bool]:
但请注意,打字不是强制的。 Python 仍然是一种动态类型语言。注释语法的开发是为了在代码发布到生产环境之前的开发过程中提供帮助。作为PEP 484 https://www.python.org/dev/peps/pep-0484/声明,“运行时不会进行类型检查。”
>>> def foo(a: str) -> list:
... return "Works"
...
>>> foo(1)
'Works'
正如您所看到的,我传递了一个 int 值并返回了一个 str。但是,那__annotations__
将被设置为相应的值。
>>> foo.__annotations__
{'return': <class 'list'>, 'a': <class 'str'>}
请通过PEP 483 https://www.python.org/dev/peps/pep-0483/有关类型提示的更多信息。另请参阅Python 3.5 中的类型提示是什么? https://stackoverflow.com/questions/32557920/what-are-type-hints-in-python-3-5?
请注意,此功能仅适用于Python 3.5并向上。这在PEP 484 https://www.python.org/dev/peps/pep-0484/.