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

Susan Sarandon
Release: 2024-11-25 15:44:11
Original
519 people have browsed it

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

Specifying Multiple Return Types with Type Hints

In Python, functions can sometimes return different data types based on the input parameters or internal logic. To clearly indicate the expected return types, type hints can be employed.

Using the Union Type

Since Python 3.10, the "|" operator can be used to create a union type. This allows multiple return types to be specified, enabling the following syntax:

def foo(id) -> list | bool:
    ...
Copy after login

This denotes that the function foo can return either a list or a boolean.

Using Typing.Union

For Python versions prior to 3.10, the typing.Union construct can be utilized:

from typing import Union

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

Limitations of Type Hints

It's important to note that type hinting in Python is not enforced at runtime. This means that type annotations serve as a guide during code development but do not guarantee the actual return types.

Demonstration:

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

>>> foo(1)
'Works'
Copy after login

In this example, an integer is passed as an argument to the function foo which is annotated to return a list. Despite violating the type annotation, the function returns a string and runs successfully.

However, the function's __annotations__ attribute will still reflect the expected return type as specified in the annotation:

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

For more information on type hints, refer to PEP 483 and What are type hints in Python 3.5??. Note that this feature is available starting from Python 3.5.

The above is the detailed content of How Can I Specify Multiple Return Types in Python 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