I come from a Typescript background. I\'m bringing static type checking into a python project I\'m working on (using mypy).
In Typescript, it is valid to return null fro
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 Optional
def 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 Union
def test(flag: bool) -> Union[str, bool]:
if flag:
return 'success'
else:
return False