Home > Article > Backend Development > How to Specify Multiple Return Types in Python Using Type Hints?
Specifying Multiple Return Types in Python Using Type Hints
In Python, functions can return values of various types. When multiple return types are possible, type hints can enhance the readability and maintainability of code.
How to Specify Multiple Return Types
From Python 3.10 onwards, the vertical bar (|) syntax can be used to specify unions. For example, the following function can return either a list or a bool:
def foo(id) -> list | bool: ...
For Python versions prior to 3.10, the typing.Union type hint can be used:
from typing import Union def foo(id) -> Union[list, bool]: ...
Example Usage
The following function retrieves an element from a list or returns False if the element is not found:
def get_element(elements, index): try: return elements[index] except IndexError: return False
Using type hints, we can specify the return types as:
def get_element(elements, index) -> list | bool: try: return elements[index] except IndexError: return False
Limitations
Type hints are not enforced at runtime. Python remains a dynamically-typed language, and type checking occurs during development. This allows flexibility but may introduce runtime errors.
Additional Information
For more information, refer to:
The above is the detailed content of How to Specify Multiple Return Types in Python Using Type Hints?. For more information, please follow other related articles on the PHP Chinese website!