pyright icon indicating copy to clipboard operation
pyright copied to clipboard

False positives with non-terminating generators

Open jonathan-laurent opened this issue 1 year ago • 3 comments

Pyright does not handle nontermination for generators in the way it does for normal functions:

# pyright: strict

from collections.abc import Generator
from typing import Never

def non_terminating() -> Generator[None, None, Never]:
    yield
    assert False

def main(x: int | None) -> Generator[None, None, int]:
    if x is None:
        yield from non_terminating()
    return x  # Spurious error: Type "int | None" is not assignable to return type "int"

Checked using Pyright 1.1.404.

jonathan-laurent avatar Aug 21 '25 08:08 jonathan-laurent

assert_never((yield from non_terminating())) can be used for workaround.

pinterior avatar Aug 23 '25 14:08 pinterior

@pinterior I did find the same workaround here, but it is verbose and should ideally not be needed (it is not needed for normal functions that are not generators).

jonathan-laurent avatar Aug 23 '25 14:08 jonathan-laurent

I came across this error today too. Here's a simplified test case that was easier for me to parse

#pyright: strict
from collections.abc import Generator
from typing import Any, NoReturn


def count() -> Generator[int, Any, NoReturn]:
    i = 0
    while True:
        yield i
        i += 1

def main() -> NoReturn:  # Spurious Error: Function with declared type "NoReturn" cannot return "None"
    for x in count():
        print(x)

anabelle2001 avatar Oct 03 '25 16:10 anabelle2001