使用 next(gen) 和 gen.send(None) 启动 Python 3 生成器之间有区别吗?

Is there a difference between starting a Python 3 generator with next(gen) and gen.send(None)?

当您创建 Python 3 生成器并立即开始 运行 时。您会收到如下错误:

TypeError: can't send non-None value to a just-started generator

为了继续(向它发送消息或从中获取信息),您首先必须对其调用 __next__next(gen) 或将 None 传递给它 gen.send(None).

def echo_back():
    while True:        
        r = yield
        print(r)

# gen is a <generator object echo_back at 0x103cc9240>
gen = echo_back()

# send anything that is not None and you get error below
# this is expected though
gen.send(1)

# TypeError: can't send non-None value to a just-started generator

# Either of the lines below will "put the generator in an active state"
# Don't need to use both
next(gen)
gen.send(None)

gen.send('Hello Stack Overflow')

# Prints: Hello Stack Overflow)

两种方式产生相同的结果(启动发电机)。

next(gen)gen.send(None) 启动发电机有什么区别?

来自generator.send()

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.

在生成器上调用 next() 开始执行,直到第一个 yield 表达式可以将非 None 值发送到其中,这将成为那个 yield 表达式(例如,x = yield)。

next(gen)gen.send(None) 的行为方式相同(即用法没有区别)。