I don't understand generator.send()
Ian Kelly
ian.g.kelly at gmail.com
Sat May 14 23:03:41 EDT 2011
On Sat, May 14, 2011 at 7:17 PM, Chris Angelico <rosuav at gmail.com> wrote:
> 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.
Yeah, that should do it. But this is so much easier to get right and
to understand:
import itertools
class Ints(object):
def __init__(self):
self.ints = itertools.count()
self.queue = []
def __iter__(self):
return self
def next(self):
if self.queue:
return self.queue.pop(0)
else:
return self.ints.next()
def insert(self, x):
self.queue.append(x)
More information about the Python-list
mailing list