Python 生成器中的 SendType 和 ReturnType

Python's SendType and ReturnType in Generators

所以我在修补生成器,我发现生成器有一个 typing 对象(即生成器有一个别名) 然后我在 https://docs.python.org/3/library/typing.html#typing.Generator 上偶然发现了 typing.Generator 对象的文档,这就是文档必须说的:

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

这让我想知道如何修改 SendTypeReturnType 东西 文档建议以此为例:

def echo_round() -> Generator[int, float, str]:
    sent = yield 0
    while sent >= 0:
        sent = yield round(sent)
    return 'Done'

我假设第二个 sent 声明定义了 SendType,但是 yield 0 returns None(或者 return 任何东西),因此引发 TypeError: '>=' not supported between instances of 'NoneType' and 'int'

SendType如何工作,如何修改它,SendTypeReturnType在什么情况下有用?

生成器有一个 send 方法:

generator.send(value)

Resumes the execution and “sends” a value into the generator function. The value argument becomes the result of the current yield expression. The send() method returns the next value yielded by the generator, or raises StopIteration if the generator exits without yielding another value. When send() is called to start the generator, it must be called with None as the argument, because there is no yield expression that could receive the value.

另见 What's the purpose of "send" function on Python generators?

因此,使用您的生成器,您可以这样做:

it = echo_round()
print(next(it))      # 0 -- we could also have printed: it.send(None) 
print(it.send(1.1))  # 1
print(it.send(2.5))  # 2
print(it.send(-1.8)) # StopIteration: Done

...but yield 0 returns None

...除非我们在第一个 yield 完成后调用 send,就像上面的脚本一样。这里 yield 0 将 return 1.1

我们在这里看到所有三种类型:

it.send(1.1) 采用 SendType 的值(在本例中为 float),returns 的值为 YieldType(在本例中为 int),或者引发 StopIteration 错误,值为 ReturnTypestr在这种情况下)。