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:
...
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:
...
The statement
def foo(client_id: str) -> list or bool:
when evaluated is equivalent todef 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):
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 withOptional[list]
From the documentation
Hence the proper way to represent more than one return data type is
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."
As you can see I am passing a int value and returning a str. However the
__annotations__
will be set to the respective values.Please Go through PEP 483 for more about Type hints. Also see What are Type hints in Python 3.5?
Kindly note that this is available only for Python 3.5 and upwards. This is mentioned clearly in PEP 484.
In case anyone landed here in search of "how to specify types of multiple return values?", use
Tuple[type_value1, ..., type_valueN]
More info: https://code-examples.net/en/q/2651e60