Named loops for breaking

bartc bartc at
Thu Mar 11 18:22:49 CET 2010

James Harris wrote:
> On 10 Mar, 06:29, "Gabriel Genellina" <gagsl-... at> wrote:
>> En Tue, 09 Mar 2010 18:41:10 -0300, Daniel Klein <bri... at>
>> escribi :
>>> Basically I'm wondering if there are any plans to implemented named
>>> loops in Python, so I can tell a break command to break out of a
>>> specific loop in the case of nested loops.
>> See PEP3136 [1] and its rejection note [2]
>> I think you may find some more discussion in the python-ideas list.

> Breaking out of an inner loop is just as natural as breaking out of
> the immediately enclosing loop. ISTM that if one is allowed the other
> should be also.

Exactly. Python already has single-level break (probably some baggage 
carried over from C), and some of the same arguments can be applied to that 

Given that break does exist, it's annoying that in the followed contrived 

def f(n):
        return n==2

for i in range(10):
        print i
        if f(0): break
        if f(1): break
        if f(2): break
        if f(3): break

I can't turn the list of ifs into a loop. I can use break embedded inside a 
statement inside a loop, provided it's not another loop! That's 

> There are often times when it *is* better to factor out the code to a
> different function but adding a function just to enable a break from
> an inner loop doesn't seem to me a good reason.

Multi-level breaks should just have been part of the language, so they are 
available to those who want them, and ignored by everyone else.

(And in languages where I've implemented them -- all generally faster than 
Python -- they have no impact on performance. I also had 4 loop controls 
rather than just 2, all multi-level, and the world hasn't ended yet.)

My experience of these break statements is that they are used infrequently 
in final code. But they are handy when developing code too: you don't want 
to waste time refactoring, and generally turning code upside-down, when the 
code has to be rewritten a dozen times anyway.


More information about the Python-list mailing list