用于生成器表达式的Python PPE 484类型注释 [英] Python's PEP 484 type annotation for Generator Expression
问题描述
例如:
def foo():
return (x*x for x in range(10))
我不知道这是-> Iterator[int]
,-> Iterable[int]
,-> Generator[int, None, None]
还是其他.
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?
推荐答案
All three forms mentioned by you in question are listed as valid alternatives in documentation, Generator expression simply creates a generator that only yields.
报价1:
可以用通用类型
Generator[YieldType, SendType, ReturnType]
注释生成器.
A generator can be annotated by the generic type
Generator[YieldType, SendType, ReturnType]
.
语录2:
如果生成器仅产生值,请设置
SendType
和ReturnType
至None
语录3:
或者,将生成器注释为返回类型为
Iterable[YieldType]
或Iterator[YieldType]
:
Alternatively, annotate your generator as having a return type of either
Iterable[YieldType]
orIterator[YieldType]
:
这篇关于用于生成器表达式的Python PPE 484类型注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!