Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

mypy complains on "Missing return statement" #137

Closed
Corwinpro opened this issue Aug 25, 2023 · 6 comments
Closed

mypy complains on "Missing return statement" #137

Corwinpro opened this issue Aug 25, 2023 · 6 comments

Comments

@Corwinpro
Copy link

Is this a known issue? What is the suggested way around this?

from result import Result, Err, Ok


def foo() -> Result[int, int]:
    return Ok(1)


def bar() -> str:
    match foo():
        case Ok(value):
            return f"{value}"
        case Err(e):
            raise RuntimeError(e)

Running mypy on this results in

example.py:8: error: Missing return statement  [return]
@wbolster
Copy link
Member

this is called an ‘exhaustiveness check’ and it can be achieved with mypy but requires more code than your example. a web search yields various articles about the details.

also read up on typing.Never in the stdlib which has an example but a rather limited explanation: https://docs.python.org/3/library/typing.html#typing.Never

@Corwinpro
Copy link
Author

@wbolster Interestingly, this passes?..

from result import Result, Err, Ok


def foo() -> Result[int, int]:
    return Ok(1)


def bar() -> str:
    result = foo()
    match result:
        case Ok(value):
            return f"{value}"
        case Err(e):
            raise RuntimeError(e)

@wbolster wbolster reopened this Aug 25, 2023
@wbolster
Copy link
Member

interesting, maybe mypy inference limitation? can you try reveal_type()?

@Corwinpro
Copy link
Author

Corwinpro commented Aug 25, 2023

But this is not result-specific, I can see the same behaviour for any Union types, as in

def foo() -> int | str: return 1
def bar() -> int:
    match foo():  # <- does not work
        case int(i): return i
        case str(s): raise ValueError(s)
def baz() -> int:
    value = foo()
    match value:  # <- does work
        case int(i): return i
        case str(s): raise ValueError(s)

@francium
Copy link
Member

francium commented Aug 25, 2023

This works,

def foo() -> int | str: return 1
def bar() -> int:
    match x := foo():
        case int(x): return x
        case str(x): raise ValueError(x)

@Corwinpro
Copy link
Author

This is actually a mypy bug: python/mypy#12998

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants