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

Barbara Streisand
Release: 2024-11-15 14:17:02
Original
1008 people have browsed it

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:
    ...
Copy after login

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

from typing import Union

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

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'
Copy after login

However, the function's annotation is preserved:

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

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.

The above is the detailed content of How Can I Specify Multiple Return Types in Python Using Type Hints?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template