I have a function in python that can either return a
bool or a
list. Is there a way to specify the return types using type hints.
For example, Is this the correct way to do it?
def foo(id) -> list or bool: ...
Solution #1:
From the documentation
class
typing.Union
Union type; Union[X, Y] means either X or Y.
Hence the proper way to represent more than one return data type is
from typing import Union def foo(client_id: str) -> Union[list,bool]
But do note that typing is not enforced. Python continues to remain a dynamically-typed language. The annotation syntax has been developed to help during the development of the code prior to being released into production. As PEP 484 states, “no type checking happens at runtime.”
def foo(a:str) -> list: return("Works") foo(1) 'Works'
As you can see I am passing a int value and returning a str. However the
__annotations__ will be set to the respective values.
.
Solution #2:
In case anyone landed here in search of “how to specify types of multiple return values?”, use
Tuple[type_value1, ..., type_valueN]
from typing import Tuple def f() -> Tuple[dict, str]: a = {1: 2} b = "hello" return a, b
More info: How to annotate types of multiple return values?
Solution #3:]
Solution #4:
Python 3.10 (use
|): Example for a function which takes a single argument that is either an
int or
str and returns either an
int or
str:
def func(arg: int | str) -> int | str: ^^^^^^^^^ ^^^^^^^^^ type of arg return type
Python 3.5 – 3.9 (use
typing.Union):
from typing import Union def func(arg: Union[int, str]) -> Union[int, str]: ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ type of arg return type
For the special case of
X | None you can use
Optional[X].
