Skip to content
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]):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you also test this with specific subtype like class MyGenerator(Generator[int, None, NoReturn])? And maybe a perverse case of class ShuffledGenerator(Generic[A, B, C], Generator[C, B, A])

...

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]