Python's PEP 484 type annotation for Generator Expression

≡放荡痞女 提交于 2019-12-19 03:21:45

问题


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))

I can't figure out if this is -> Iterator[int], -> Iterable[int], -> Generator[int, None, None], or something else.

If there should be one-- and preferably only one --obvious way to do it, then what is the obvious way here?


回答1:


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]:



来源:https://stackoverflow.com/questions/42227288/pythons-pep-484-type-annotation-for-generator-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!