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:
...
This question is related to
python
python-3.x
return-type
type-hinting
python-3.5
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]
.
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
The statement def foo(client_id: str) -> list or bool:
when evaluated is equivalent to
def foo(client_id: str) -> list:
and will therefore not do what you want.
The native way to describe a "either A or B" type hint is Union (thanks to Bhargav Rao):
def foo(client_id: str) -> Union[list, bool]:
I do not want to be the "Why do you want to do this anyway" guy, but maybe having 2 return types isn't what you want:
If you want to return a bool to indicate some type of special error-case, consider using Exceptions instead. If you want to return a bool as some special value, maybe an empty list would be a good representation.
You can also indicate that None
could be returned with Optional[list]
Source: Stackoverflow.com