Python's PEP 484 type annotation for Generator Expression

前端 未结 1 1679
逝去的感伤
逝去的感伤 2021-01-04 08:52

What is the correct type annotation for a function that returns a generator expression?

e.g.:

def foo():
    return (x*x for x in range(10))
         


        
1条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-04 09:27

    All three forms mentioned by you in question are listed as valid alternatives in documentation, Generator expression simply creates a generator that only yields.

    Quote 1:

    A generator can be annotated by the generic type Generator[YieldType, SendType, ReturnType].

    Quote 2:

    If your generator will only yield values, set the SendType and ReturnType to None

    Quote 3:

    Alternatively, annotate your generator as having a return type of either Iterable[YieldType] or Iterator[YieldType]:

    0 讨论(0)
提交回复
热议问题