basedpyright icon indicating copy to clipboard operation
basedpyright copied to clipboard

generator with return type of `Never` should treat the code after the iteration as unreachable unless the loop contains a `break` statement, and not treat variables assigned within the loop as possibly unbound

Open DetachHead opened this issue 3 months ago • 0 comments

Description

Code sample in basedpyright playground

from collections.abc import Generator
from typing import Never, reveal_type


def iter() -> Generator[int, None, Never]:
    yield 1
    raise Exception


for value in iter():
    foo = value
    break 

reveal_type(foo)  # Unbound | Literal[1, 2]

in this example, if foo is unbound that would mean the generator iterated 0 times and therefore would have raised an exception, meaning this line is unreachable unless the generator iterated at least once and a break statement was reached.

DetachHead avatar Nov 06 '25 04:11 DetachHead