I don't understand generator.send()

Chris Angelico rosuav at gmail.com
Sat May 14 21:17:31 EDT 2011


On Sun, May 15, 2011 at 11:05 AM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
> Actually, this won't work, because the value of the "yield None" gets
> ignored.  Thus if you try to call send() twice in a row, the generator
> the treats second send() as if it were a next(), and it is not
> possible to have more than one item in the queue.

You're right. It needs a while loop instead of the if (and some slight
reordering):

def ints():
   i=0
   queue=[]
   while True:
       if queue:  # see other thread, this IS legal and pythonic and
quite sensible
           sent=(yield queue.pop(0))
       else:
           sent=(yield i)
           i+=1
       while sent is not None:
           queue.append(sent)
           sent=(yield None)  # This is the return value from gen.send()

That should work.

Chris Angelico



More information about the Python-list mailing list