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

While loop prevents triggering "no return statement" #17014

Open
sebsheep opened this issue Mar 11, 2024 · 3 comments
Open

While loop prevents triggering "no return statement" #17014

sebsheep opened this issue Mar 11, 2024 · 3 comments
Labels
bug mypy got something wrong

Comments

@sebsheep
Copy link

Bug Report

A while loop in a function prevents mypy to detect a missing return statement.

To Reproduce
https://mypy-play.net/?mypy=latest&python=3.12&flags=strict&gist=363627f969a9a127616dd5ee7ea2a235

def f() -> int:
    b = None
    while not b:
        b = 1

Expected Behavior

In strict mode, mypy should raise an error because f doesn't return
Actual Behavior

Mypy successes!

Your Environment

  • Mypy version used: 1.8.0
  • Mypy command-line flags: --stric
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.12
@sebsheep sebsheep added the bug mypy got something wrong label Mar 11, 2024
@KotlinIsland
Copy link
Contributor

More generally, the type of the while subject does not get updated from the body:

b = None
reveal_type(b)  # None from ? | None
while not b:
    reveal_type(b)  # None from ? | None
    b = 1
    reveal_type(b)  # int from int | None
reveal_type(b)  # unreachable

https://mypy-play.net/?mypy=basedmypy-latest&python=3.12&flags=strict&gist=363627f969a9a127616dd5ee7ea2a235

@sebsheep
Copy link
Author

even if the while subject we had a true infinite loop, this function never returns... Is this the expected behavior?

def f() -> int:
    while True:
        pass

type checks!

@KotlinIsland
Copy link
Contributor

KotlinIsland commented Mar 12, 2024

Yes, that is intended, because it is technically correct, consider:

def f() -> Never:
    while True: ...

This doesn't produce any error because the function will Never return.

But perhaps it should warn here when the return type of the function is not Never, something like:

def f() -> int:
   while True:  # this loop will never return
       ...

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

No branches or pull requests

2 participants