Skip to content

Mark code after for loops that never end as unreachable #19287

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

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -5108,12 +5108,26 @@ def visit_for_stmt(self, s: ForStmt) -> None:
s.inferred_item_type = item_type
s.inferred_iterator_type = iterator_type

proper_iter_type = get_proper_type(iterator_type)
if isinstance(proper_iter_type, Instance) and any(
base.fullname == "typing.Generator" for base in proper_iter_type.type.mro
):
supertype = self.named_type("typing.Generator").type
super_instance = map_instance_to_supertype(proper_iter_type, supertype)
if isinstance(get_proper_type(super_instance.args[2]), UninhabitedType):
exit_condition = IntExpr(1)
else:
exit_condition = IntExpr(0)
else:
exit_condition = IntExpr(0)

self.accept_loop(
s.body,
s.else_body,
on_enter_body=lambda: self.analyze_index_variables(
s.index, item_type, s.index_type is None, s
),
exit_condition=exit_condition,
)

def analyze_async_iterable_item_type(self, expr: Expression) -> tuple[Type, Type]:
Expand Down
48 changes: 48 additions & 0 deletions test-data/unit/check-unreachable-code.test
Original file line number Diff line number Diff line change
Expand Up @@ -1587,3 +1587,51 @@ x = 0 # not unreachable

f2: Callable[[], NoReturn] = lambda: foo()
x = 0 # not unreachable

[case testUnendingForLoop]
# flags: --warn-unreachable
from typing import Generator, NoReturn, TypeVar

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

def foo() -> int:
for x in generator():
return x

y = 0 # E: Statement is unreachable

def bar() -> int: # E: Missing return statement
for x in generator():
break

y = 0

def baz() -> int:
for x in generator():
pass

A = TypeVar("A")
B = TypeVar("B")
C = TypeVar("C")

class GeneratorSubtype(Generator[A, B, C]):
...

def foo2(gen: GeneratorSubtype[int, None, NoReturn]) -> int:
for x in gen:
return x

y = 0 # E: Statement is unreachable

def bar2(gen: GeneratorSubtype[int, None, NoReturn]) -> int: # E: Missing return statement
for x in gen:
break

y = 0

def baz2(gen: GeneratorSubtype[int, None, NoReturn]) -> int:
for x in gen:
pass
[builtins fixtures/tuple.pyi]