用于生成器表达式的Python PPE 484类型注释 [英] Python's PEP 484 type annotation for Generator Expression

查看:107
本文介绍了用于生成器表达式的Python PPE 484类型注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

返回生成器表达式的函数的正确类型注释是什么? ?

例如:

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:

如果生成器仅产生值,请设置SendTypeReturnTypeNone

语录3:

或者,将生成器注释为返回类型为 Iterable[YieldType]Iterator[YieldType]:

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

这篇关于用于生成器表达式的Python PPE 484类型注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆