I am getting a MyPy error "Missing return statement", even when I check for all possible cases inside a function.
For example, in the following code, MyPy is still giving me an error "9: error: Missing return statement"
, even though color
can only be Color.RED
, Color.GREEN
, or Color.BLUE
, and I test all those cases!
class Color(enum.IntEnum):
RED: int = 1
GREEN: int = 2
BLUE: int = 3
def test_enum(color: Color) -> str:
if color == Color.RED:
return "red"
elif color == Color.GREEN:
return "green"
elif color == Color.BLUE:
return "blue"
It’s easy to see that any statement after return is unreachable, and hence mypy will not complain about the mis-typed code below it. For a more subtle example, consider this code: Again, mypy will not report any errors. The type of foo.bar is str, and mypy reasons that it can never be None.
A method does not have a return statement, while the declaration requires one. The declaration states that the method returnTest () returns a String value, but because in the declaration no return statement is provided, the compiler throws the Missing return Statement Error.
This error can be caused by, as the error name suggests, when the return statement is missing from the program. Missing return statement error can be thrown due to the following possible reasons:
It’s easy to see that any statement after return is unreachable, and hence mypy will not complain about the mis-typed code below it. For a more subtle example, consider this code:
There really is no question in this question - mypy indeed behaves this way at the moment. The enum support is baked in, and is preliminary and somewhat ad-hoc. The kind of checking you are looking for might be implemented in the future.
However, this code is fragile; if Color will change, it will silently break. Remember that Python is not a compiled language - the typechecker pass is optional, and someone else might not use it.
The right way IMO is to add assert False
at the end. This will also silence mypy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With