typing.Generator 的第二个和第三个类型参数是什么意思?
What do the second and third type parameters to typing.Generator mean?
编写以下代码
def a(n: int):
for i in range(n):
yield i
b = a(3)
然后要求 PyCharm 向变量添加类型提示 b
将变量声明变为
b: Generator[int, Any, None] = a(3)
Any
和None
代表什么?为什么 Generator
采用这些类型参数?
第二个和第三个类型参数代表生成器send
取的类型,生成器returns.
取的类型
send
是 Python 2.5 中作为 PEP 342, which extended generators to work as coroutines. In PEP 342, yield
becomes an expression, and send
is like next
, but specifying a value for the yield
expression the generator is suspended at. (If the generator is suspended at the beginning rather than at a yield
, a non-None value cannot be sent into it.) Looking at the example in the typing.Generator
docs:
的一部分引入的功能
def echo_round() -> Generator[int, float, str]:
sent = yield 0
while sent >= 0:
sent = yield round(sent)
return 'Done'
此生成器在 send
中采用浮点数,return 是 send
参数的舍入值。
生成器 return 值在 Python 3.3 中作为 PEP 380 的一部分引入,作为子生成器委托支持的一部分。在 PEP 380 之前,将一个生成器分成多个函数是非常尴尬的,部分原因是子生成器没有像 return
这样的机制将结果传回给它们的调用者。使用 PEP 380,生成器可以 return
一个值,该值将用作从生成器生成的 yield from
表达式的值。在 typing.Generator
文档示例中,echo_round
return 是一个字符串。
编写以下代码
def a(n: int):
for i in range(n):
yield i
b = a(3)
然后要求 PyCharm 向变量添加类型提示 b
将变量声明变为
b: Generator[int, Any, None] = a(3)
Any
和None
代表什么?为什么 Generator
采用这些类型参数?
第二个和第三个类型参数代表生成器send
取的类型,生成器returns.
send
是 Python 2.5 中作为 PEP 342, which extended generators to work as coroutines. In PEP 342, yield
becomes an expression, and send
is like next
, but specifying a value for the yield
expression the generator is suspended at. (If the generator is suspended at the beginning rather than at a yield
, a non-None value cannot be sent into it.) Looking at the example in the typing.Generator
docs:
def echo_round() -> Generator[int, float, str]:
sent = yield 0
while sent >= 0:
sent = yield round(sent)
return 'Done'
此生成器在 send
中采用浮点数,return 是 send
参数的舍入值。
生成器 return 值在 Python 3.3 中作为 PEP 380 的一部分引入,作为子生成器委托支持的一部分。在 PEP 380 之前,将一个生成器分成多个函数是非常尴尬的,部分原因是子生成器没有像 return
这样的机制将结果传回给它们的调用者。使用 PEP 380,生成器可以 return
一个值,该值将用作从生成器生成的 yield from
表达式的值。在 typing.Generator
文档示例中,echo_round
return 是一个字符串。