[Python] mypy complains about missing return when the function implicitly returns None

Discussão em 'Python' iniciado por Stack, Abril 24, 2025.

  1. Stack

    Stack Membro Participativo

    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

    Continue reading...

Compartilhe esta Página