python / python/mypy

For loop with a `Generator[Any, Any, NoReturn]` doesn't cause unreachable code.

Open
#18,891 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-reachability
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

A for loop iterating over a Generator[Any, Any, NoReturn] isn't assumed to continue indefinitely.

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.12&gist=cd9b4f28655f7a5460983d6c9a520331

from typing import Generator, NoReturn

def generator() -> Generator[int, None, NoReturn]:
    while True:
        yield 1

def foo() -> int:
    for x in generator():
        return x
    # Code past this point should be unreachable.
    # But mypy expects a return statement here.

Expected Behavior

Any code following for loops that iterate over unending generators should be recognized as unreachable, and the execution shouldn't branch.

Actual Behavior

main.py:7: error: Missing return statement  [return]

Your Environment

  • Mypy version used: 1.15.0
  • Python version used: 3.12

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the Python reproducer in the issue's mypy-play link and the reported main.py example, then trace mypy's handling of for loops over generators annotated with NoReturn. The fix is complete when code after an unending generator loop is treated as unreachable and the example no longer reports a missing return statement.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
55/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.