Domanda

Here is the code (courtesy of David Beazley, slide #32 http://dabeaz.com/coroutines/Coroutines.pdf):

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

c = countdown(5)
for n in c:
  print n
  if n == 5:
    c.send(3)

And here's the output: http://codepad.org/8eY3HLsK

I understand that it doesn't print 4, but why doesn't it print 3? Once n is set to 3, the next iteration should yield 3 and not 2? What am I missing?

È stato utile?

Soluzione

As documented, sending a value to a generator also causes the generator to advance one more step and yield its next value. The value 3 is yielded at the line c.send(3), but you don't do anything with it so you don't see it. Then on the next trip through the while loop it keeps counting down from there. If you change your last line to print c.send(3) then you will see the 3.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top