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 from a function that is annotated to return something else, i.e. a string:
function test(flag: boolean): string {
if(flag) {
return 'success';
} else {
return null;
}
}
It is also valid to annotate your function to have multiple potential return types, i.e. string or boolean:
function test(flag: boolean): string | boolean {
if(flag) {
return 'success';
} else {
return false;
}
}
But, in python using mypy, I'm disallowed from returning None from a function that is annotated to return str.
def test(flag: bool) -> str:
if flag:
return 'success'
else:
return None
# [mypy] error:Incompatible return value type (got "None", expected "str")
Furthermore, I don't see a way to annotate multiple return types, i.e. str | None.
How should I approach something like this using mypy? Functions that return None from the error state are all over my codebase.