Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I declare the type of a python generator [duplicate]

Python 3.x supports (optional) function annotations:

def add_ints(x: int, y: int) -> int:
    return x + y

I sometimes encounter problems as to how to represent a given "type", and this time, I have a function that returns a generator:

def myfunc(x: [int]) -> "generator that returns ints":
    #                    ^~~~~~~~~~~~~~~~~~~~~~~~~~
    return (n for n in x if n % 2 == 0)

How should I annotate the return value?

like image 729
Yosh Avatar asked Mar 18 '26 00:03

Yosh


1 Answers

While Generator[x, y, z] exists, most of the time, you might want to use the less verbose Iterator:

from collections.abc import Iterator

def fn(x: int) -> Iterator[int]:
    return (n for n in range(x) if n%2 == 0)

It also works for yield:

def fn(x: int) -> Iterator[int]:
    for n in range(x):
        yield n
like image 59
Conchylicultor Avatar answered Mar 19 '26 12:03

Conchylicultor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!