[Python-ideas] iterating over a generator while sending values
Greg Ewing
greg.ewing at canterbury.ac.nz
Fri Mar 28 00:17:43 CET 2014
Clay Gerrard wrote:
> def consume(q):
> success = None
> while True:
> try:
> item = q.send(success)
> except StopIteration:
> break
> success = handle(item)
My first thought would be to ask whether you really need
to do things this way round. Instead of the consumer pulling
things from the producer, can you have the producer push
them to the consumer? Then the response is just a function
return value.
Assuming you do need to pull, my solution would be
something like this (not tested):
class Feedbackerator:
def __init__(self, base):
self.base = base
self.response = None
def __next__(self):
return self.base.send(self.response)
def consume(q):
f = Feedbackerator(q)
for item in f:
f.response = handle(item)
--
Greg
More information about the Python-ideas
mailing list