Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #5586

Re: in search of graceful co-routines

Newsgroups comp.lang.python
Date 2011-05-17 10:30 -0700
Subject Re: in search of graceful co-routines
From Carl Banks <pavlovevidence@gmail.com>
Message-ID <mailman.1683.1305653427.9059.python-list@python.org> (permalink)

Show all headers | View raw


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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: in search of graceful co-routines Carl Banks <pavlovevidence@gmail.com> - 2011-05-17 10:30 -0700

csiph-web