从PEP342:
Because generator-iterators begin execution at the top of the generator's function body, there is no yield expression to receive a value when the generator has just been created. Therefore, calling send() with a non-None argument is prohibited when the generator iterator has just started, ...
例如
>>> def a():
... for i in range(5):
... print((yield i))
...
>>> g = a()
>>> g.send("Illegal")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't send non-None value to a just-started generator
为什么这是非法的?我在这里理解yield
的用法,它暂停函数的执行,并在下次调用next()
(或send()
)时返回到该点。但是打印(yield i)
的第一个结果似乎是合法的?你知道吗
以另一种方式问:g = a()
后面的生成器“g”处于什么状态。我假设它一直运行a()
,直到第一个yield,并且由于有yield,它返回一个生成器,而不是标准的同步对象返回。你知道吗
那么,为什么在新生成器上使用非None参数调用send是非法的呢?
注意:我已经阅读了this question的答案,但并没有真正触及为什么在新生成器上调用send(非None)是非法的。你知道吗
不,就在
g = a()
之后,就在函数的开头。直到您将生成器提前一次(通过调用next(g)
),它才会运行到第一个产量。你知道吗这是您在问题中引用的内容:“因为生成器迭代器从生成器函数体的顶部开始执行…”它在PEP 255中也这样说,它引入了生成器:
请注意,yield语句是否实际执行并不重要。仅仅在函数体中出现
yield
就可以使函数成为生成器,如documented:相关问题 更多 >
编程相关推荐