0

simple question : What is the correct PEP 3107 keyword for a function that yields items ?

Already tried this, but it doesn't work

def this_function() -> generator:
    for x in range(0,100):
        yield x

Also tried with Iterator[int] as this post suggests, but no results. Also tried the various propositions made here, but nothing

N.B. Don't know if this is relevant, but my linter is Pylance on VSCode

1 Answers1

0

You can use collections.abc.Generator

from collections.abc import Generator

def this_function() -> Generator[int, None, None]:
    for x in range(0, 100):
        yield x

Or simply: collections.abc.Iterator or collections.abc.Iterable.

from collections.abc import Iterable

def this_function() -> Iterable[int]:
    for x in range(0, 100):
        yield x
Jab
  • 26,853
  • 21
  • 75
  • 114
  • Note that the documentation also sanctions the use of `Iterator[X]` or `Iterable[X]` in place of `Generator[X, None, None]`. – chepner Jun 05 '23 at 14:32
  • (Also, `typing.Generator` is deprecated in favor of `collections.abc.Generator`. `typing` versions of various collections were only needed because the abstract classes weren't generic until Python 3.9.) – chepner Jun 05 '23 at 14:33
  • Thank you @chepner I was definitely behind the times. – Jab Jun 05 '23 at 15:36