in search of graceful co-routines

Carl Banks pavlovevidence at gmail.com
Tue May 17 13:30:25 EDT 2011


On Tuesday, May 17, 2011 10:04:25 AM UTC-7, Chris Withers wrote:
> Now, since the sequence is long, and comes from a file, I wanted the 
> provider to be an iterator, so it occurred to me I could try and use the 
> new 2-way generator communication to solve the "communicate back with 
> the provider", with something like:
> 
> for item in provider:
>    try:
>      consumer.handleItem(self)
>    except:
>       provider.send('fail')
>    else:
>       provider.send('succeed')
> 
> ..but of course, this won't work, as 'send' causes the provider 
> iteration to continue and then returns a value itself. That feels weird 
> and wrong to me, but I guess my use case might not be what was intended 
> for the send method.

You just have to call send() in a loop yourself.  Note that you should usually catch StopIteration whenever calling send() or next() by hand.  Untested:

result = None
while True:
    try:
        item = provider.send(result)
    except StopIteration:
        break
    try:
        consumer.handleItem(item)
    except:
        result = 'failure'
    else:
        result = 'success'


Carl Banks



More information about the Python-list mailing list