[Python-ideas] iterating over a generator while sending values

Anthony Towns aj at erisian.com.au
Fri Mar 28 05:22:01 CET 2014


On 28 March 2014 09:17, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> Clay Gerrard wrote:
>> def consume(q):
>>     success = None
>>     while True:
>>         try:
>>             item = q.send(success)
>>         except StopIteration:
>>             break
>>         success = handle(item)
>
> 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)

Ooo, nice. Minor tweaks to make it work in py2, and not require you to
set the response every iteration:

class Feedbackerator(object):
    def __init__(self, iterator):
        self.iter = iter(iterator)
        self.resp = None
    def next(self):
        r, self.resp = self.resp, None
        return self.iter.send(r)
    def __iter__(self):
        return self

def consume(q):
    qi = Feedbackerator(q)
    for item in qi:
        res = handle(item)
        if needs_feedback(res):
            qi.resp = feedback_for(res)

Cheers,
aj

-- 
Anthony Towns <aj at erisian.com.au>


More information about the Python-ideas mailing list