[python] How to specify multiple return types using type-hints

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

The answer is


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

More info: How to annotate types of multiple return values?


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]


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to python-3.x

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation Replace specific text with a redacted version using Python Upgrade to python 3.8 using conda "Permission Denied" trying to run Python on Windows 10 Python: 'ModuleNotFoundError' when trying to import module from imported package What is the meaning of "Failed building wheel for X" in pip install? How to downgrade python from 3.7 to 3.6 I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? Iterating over arrays in Python 3 How to upgrade Python version to 3.7?

Examples related to return-type

How to specify multiple return types using type-hints Return from lambda forEach() in java Return different type of data from a method in java? Apply pandas function to column to create multiple new columns? C++: variable 'std::ifstream ifs' has initializer but incomplete type Returning anonymous type in C# How do I make the return type of a method generic? How to return result of a SELECT inside a function in PostgreSQL? Can two Java methods have same name with different return types? What should main() return in C and C++?

Examples related to type-hinting

Adding default parameter value with type hint in Python How to specify multiple return types using type-hints What are type hints in Python 3.5? How to resolve "must be an instance of string, string given" prior to PHP 7?

Examples related to python-3.5

ImportError: No module named 'django.core.urlresolvers' 'python3' is not recognized as an internal or external command, operable program or batch file pip not working in Python Installation in Windows 10 installing cPickle with python 3.5 Difference between numpy dot() and Python 3.5+ matrix multiplication @ How to specify multiple return types using type-hints What are type hints in Python 3.5?