[Python-ideas] Loop labels
steve at pearwood.info
Fri Mar 9 10:18:42 CET 2012
On Fri, Mar 09, 2012 at 07:06:47AM +0200, David Townshend wrote:
> The biggest problem is not the new syntax. It's the new type of object
> that would be needed, Label, which lies in some magical place half way
> between a name and a keyword.
Labels are neither names nor keywords nor objects. They would be
instructions to the compiler, nothing more.
The idea of labelled break/continue is not a new invention. Before
criticising it (or for that matter, praising it), we should see how it
works in other languages.
Java has labelled loops:
> What would be the result of the following code?
> loops = 
> for i in range(4) as label:
> print(type(label), dir(label))
NameError, because there is no name "label".
> for label in loops as newlabel:
> break label
SyntaxError, because the "label" loop is not enclosing the break.
For what it's worth, I used to be against this idea as adding
unnecessary complexity, until a year or so ago when I came across a
use-case which was naturally written as nested loops with labelled
breaks. Now I'm sold on the idea. I ended up re-writing the code to use
functions, but it really wasn't natural. It felt forced.
I just wish I could remember what the algorithm was... :(
More information about the Python-ideas