So, my question is regarding a code that looks like this:
def f(condition: bool) -> int | None:
if condition:
return 1
def g(condition: bool) -> int | None:
if condition:
return
return 1
This is clearly valid python code, the idea is that the function will try to do something, if it succeeds it will return the result, but if it fails will return None
My problem is that mypy complains with the following error:
1: error: Missing return statement [return]
7: error: Return value expected [return-value]
Now, python will always implicitly return None when a function is missing a return statement, which is what I am using in my function.
My question is, is there any option in mypy to (with minimal or no changes to the code) tell it to stop complaining about this valid code?
To be clear, I would still want it to complain about this code:
def f(condition: bool) -> int:
if condition:
return 1
def g(condition: bool) -> int:
if condition:
return
return 1
Provide an explicit return
statement when the if
statement does not match in the first function and explicitly return None
in the second function:
def f(condition: bool) -> int | None:
if condition:
return 1
return None
def g(condition: bool) -> int | None:
if condition:
return None
return 1
If you want to silence the first error without changing the code then you can use the --no-warn-no-return
option.
If you want to locally silence the return
error on line 1 and the return-value
error on line 7 then you can use:
def f(condition: bool) -> int | None: # type: ignore[return]
if condition:
return 1
def g(condition: bool) -> int | None:
if condition:
return # type: ignore[return-value]
return 1
(But it is less to type to provide explicit None
return values.)