值在python生成器/协同程序中丢失 [英] Value get lost in python generator/coroutine
问题描述
我正在查看 http://www.dabeaz.com/coroutines/ ,其中我我发现非常有趣,但在一个例子中有一种我不理解的行为。
I was looking at http://www.dabeaz.com/coroutines/, which I am finding very interesting, but in an example there is a behavior I do not understand.
在 bogus.py 示例,此处报告
# bogus.py
#
# Bogus example of a generator that produces and receives values
def countdown(n):
print "Counting down from", n
while n >= 0:
newvalue = (yield n)
# If a new value got sent in, reset n with it
if newvalue is not None:
n = newvalue
else:
n -= 1
# The holy grail countdown
c = countdown(5)
for x in c:
print x
if x == 5:
c.send(3)
数字序列生成的是5,2,1,0,我无法理解在哪里数字3消失了:在 send(3)
之后,变量 n
被正确设置,但是在第二个执行 yield
,看起来值3只是非屈服于for循环。
The sequence of numbers generated is 5, 2, 1, 0, and I can not understand where the number 3 is gone: after the send(3)
, the variable n
is correctly set, but at the second execution of yield
, it looks like the value 3 is just non yielded to the for loop.
有人可以澄清我为什么会这样?
Can someone clarify me why this happen?
推荐答案
从<$返回 3
c $ c> .send(),但丢弃了。生成器生成 5
, 3
, 2
, 1
, 0
;但由于 3
返回到 .send()
调用,因此您看不到打印的值。 循环的永远不会看到它。
The 3
was returned from .send()
, but discarded. The generator produces 5
, 3
, 2
, 1
, 0
; but because the 3
is returned to the .send()
call you don't see that value printed. The for
loop never gets to see it.
这是怎么回事:
- 第一次
for
循环调用next()
on生成器,代码前进,直到5
得到。 -
x == 5
是True
,因此调用c.send(3)
。代码通过生成器函数前进,newvalue
设置为3
。 - 生成器不暂停,它现在有控制权。生成器运行
而
循环并返回(yield n)
表达式。产生了3
。它成为c.send(3)
的返回值。这里将丢弃返回值。 - 循环的
继续,调用
next()
再次。再次继续生成器yield
返回无
,循环到n - = 1
并且屈服2
。 -
for
循环继续在生成器上调用next()
,1
和0
产生,生成器结束。
- first time the
for
loop callsnext()
on the generator, the code advances until5
is yielded. x == 5
isTrue
, soc.send(3)
is called. The code advances through the generator function, andnewvalue
is set to3
.- The generator does not pause there, it now has control. The generator runs through the
while
loop and comes back to the(yield n)
expression.3
is yielded. It becomes the return value forc.send(3)
. The return value is discarded here. - The
for
loop continues, callsnext()
again. The generator is continued again withyield
returningNone
, loops round ton -= 1
and yielding2
. - The
for
loop continues to callnext()
on the generator,1
and0
are yielded, the generator ends.
恢复执行并将值发送到生成器函数中。
值
参数成为当前yield
表达式的结果。send()
方法返回生成器产生的下一个值,或者引发StopIteration
如果生成器退出而没有产生另一个值。
Resumes the execution and "sends" a value into the generator function. The
value
argument becomes the result of the currentyield
expression. Thesend()
method returns the next value yielded by the generator, or raisesStopIteration
if the generator exits without yielding another value.
强调我的。
这篇关于值在python生成器/协同程序中丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!