[Python-ideas] Loop labels
Matt Joiner
anacrolix at gmail.com
Thu Mar 8 19:52:08 CET 2012
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
More information about the Python-ideas
mailing list