[Python-ideas] Extended "break" "continue" in "for ... in" block.

Nick Coghlan ncoghlan at gmail.com
Thu May 24 14:21:43 CEST 2012


On Thu, May 24, 2012 at 9:26 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> 海韵 wrote:
>>
>> Hi all...
>> i'd like to propose a syntax extend of "break" and  "continue"
>> to let them work together with "yield".
>
> Can you give an example of how you would use them, and why?

It's an approach to driving a coroutine (and one that was discussed
back when the coroutine methods were added to generators). Currently,
if you're using a generator as a coroutine, you largely *avoid* using
it directly as an iterator. Aside from the initial priming of
coroutines, most generator based code will either treat them as
iterators (via for loops, comprehensions and next() calls), or as
coroutines (via send() and throw() calls).

The main reason tinkering with for loops has been resisted is that
native support for even "continue <value>" (the least controversial
part of the suggestion) would likely result in slowing down all for
loops to cover the relatively niche coroutine use case.

Also, if anything was going to map to throw() it would be "continue
raise", not "break":

continue -> next(itr)
continue <value> -> itr.send(<value>)
continue raise <exc> -> itr.throw(<value>)

So yeah, this isn't a new proposal, but what's still lacking is a
clear justification of what code will actually *gain* from the
increase in the language complexity. How often are generator based
coroutines actually used outside the context of a larger framework
that already takes care of the next/send/throw details?

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia



More information about the Python-ideas mailing list