Home >Backend Development >Python Tutorial >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: ...
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]: ...
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'
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'>}
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!