如何使用型別提示在 Python 中指定多個回傳類型?

Barbara Streisand
發布: 2024-11-15 14:17:02
原創
1008 人瀏覽過

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板