[Python-ideas] Loop labels

Westley Martínez anikom15 at gmail.com
Fri Mar 9 00:06:47 CET 2012


On Fri, Mar 09, 2012 at 02:52:08AM +0800, Matt Joiner wrote:
> Several languages allow break and continue statements to take a count
> or loop label for greater flexibility.
> 
> Dealing with nested loops and control flow around them is definitely
> something I and probably most programmers deal with everyday.
> Generally for very complex control flow one might employ functions,
> and use return statements to work around any shortcomings. This is not
> always ideal in CPython because of the performance cost of function
> calls, and lack of anonymous functions. The other work around is
> usually goto statements, which clearly aren't available or appropriate
> in Python.
> 
> So what about the following extensions?
> 
> Allow for and while statements to be labelled using "as".
> 
> Allow break and continue to take the name of a containing loop, or an
> integer. The corresponding named loop, or the nth containing loop are
> treated as though they are the nearest enclosing loop.
> 
> loop_label ::=  identifier
> 
> break_stmt ::=  "break" [decimalinteger | loop_label]
> 
> continue_stmt ::=  "continue" [decimalinteger | loop_label]
> 
> while_stmt ::=  "while" expression ["as" loop_label] ":" suite
>                 ["else" ":" suite]
> 
> for_stmt ::=  "for" target_list "in" expression_list ["as" loop_label] ":" suite
>               ["else" ":" suite]
> 
> Here's a really naive example:
> for a in b as c:
>     for d in e:
>         break c # or break 2
>     for f in g:
>         continue c # or continue 2

-1; if we do this we might as well add goto labels.



More information about the Python-ideas mailing list