首页  >  文章  >  后端开发  >  如何使用类型提示在 Python 中指定多个返回类型?

如何使用类型提示在 Python 中指定多个返回类型?

Barbara Streisand
Barbara Streisand原创
2024-11-15 14:17:02979浏览

How Can I Specify Multiple Return Types in Python Using Type Hints?

Combining Return Types in Python Using Type-Hints

In Python, functions can return one of several types. Specifying these return types using type-hints increases code clarity and allows for earlier error detection.

To specify multiple return types, use the | (bitwise OR) operator for Python 3.10 and above:

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

Before Python 3.10, use the Union type from the typing module:

from typing import Union

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

Note that type-checking is not enforced during runtime. Type-hints serve as guidelines for code development, providing enhanced clarity and aiding in earlier detection of potential issues. For example, even though foo is annotated with str input and list output, the following code executes successfully, returning a str:

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

>>> foo(1)
'Works'

However, the function's annotation is preserved:

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

Refer to PEP 483 for further details on type-hints and PEP 484 for the introduction of | syntax for return types in Python 3.10.

以上是如何使用类型提示在 Python 中指定多个返回类型?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn