Search code examples
pythonpython-typingmypy

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"

Solution

  • 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.