How to annotate a generator in python3?

后端 未结 2 788
庸人自扰
庸人自扰 2021-02-12 11:06

Python 3.x supports (optional) function annotations:

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

I sometimes encounter problems as to

2条回答
  •  时光取名叫无心
    2021-02-12 11:26

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

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

    Also works for yield

    def add_ints(x: int) -> Iterator[int]:
        for n in range(x):
            yield n
    

提交回复
热议问题