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

前提是你 提交于 2019-12-13 14:15:46

问题


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"

回答1:


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.



来源:https://stackoverflow.com/questions/47149154/mypy-gives-error-missing-return-statement-even-when-all-cases-are-tested

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!