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

时间:2015-04-27 22:25:58

标签: python-3.x yield coroutine

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

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

为了前往(向其发送消息或从中获取消息),您首先必须在其上调用__next__next(gen)或向其传递无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)启动生成器之间有什么区别?

1 个答案:

答案 0 :(得分:0)

来自generator.send()

  

当调用send()来启动生成器时,必须使用None作为参数调用它,因为没有可以接收值的yield表达式。

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

x = yieldnext(gen)的行为方式相同(即使用方式没有差异)。