Return None from python function annotated with mypy, multiple return types Return None from python function annotated with mypy, multiple return types python python

Return None from python function annotated with mypy, multiple return types


Okay, I found what I was missing in the documentation thanks to @zsol on the mypy gitter!

Two helpful mypy features are the Optional and Union types that can be imported from python's typing module. Documentation here.

If you want to annotate that the function can potentially return None in addition to the primary type, e.g. str, use Optional:

from typing import Optionaldef test(flag: bool) -> Optional[str]:    if flag:        return 'success'    else:        return None

If you want to annotate that the function can potentially return multiple types, e.g. str | bool, use Union:

from typing import Uniondef test(flag: bool) -> Union[str, bool]:    if flag:        return 'success'    else:        return False