Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MyPy gives error "Missing return statement" even when all cases are tested

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"
like image 511
ostrokach Avatar asked Nov 07 '17 02:11

ostrokach


People also ask

Why doesn’t mypy report any errors?

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.

Why is returntest () not returning a string?

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.

What is a 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:

Does mypy complain about mis-typed code below it?

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:


1 Answers

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.

like image 170
Elazar Avatar answered Oct 28 '22 02:10

Elazar