Naming Loops in Python Naming Loops in Python python python

Naming Loops in Python


Here's a way to break out of multiple, nested blocks using a context manager:

import contextlib@contextlib.contextmanagerdef escapable():    class Escape(RuntimeError): pass    class Unblock(object):        def escape(self):            raise Escape()    try:        yield Unblock()    except Escape:        pass

You can use it to break out of multiple loops:

with escapable() as a:    for i in xrange(30):        for j in xrange(30):            if i * j > 6:                a.escape()

And you can even nest them:

with escapable() as a:    for i in xrange(30):        with escapable() as b:            for j in xrange(30):                if i * j == 12:                    b.escape()  # Break partway out                if i * j == 40:                    a.escape()  # Break all the way out


Though there are reasons to include named looped in language construct you can easily avoid it in python without loss of readability.An implementation of the referred example in python

>>> try:    for i in xrange(0,5):        for j in xrange(0,6):            if i*j > 6:                print "Breaking"                raise StopIteration            print i," ",jexcept StopIteration:    print "Done"0   00   10   20   30   40   51   01   11   21   31   41   52   02   12   22   3BreakingDone>>> 

I solve this problem by putting the inner loop in a function that returns (among others) a boolean which is used as a breaking condition.

I think you should try this. This is very pythonic, simple and readable.


There was a proposal to include named loops in python PEP3136, however, it was rejected with an explanation here. The rejection was mostly due to the rare number of circumstances where code readability would be improved by including this construct.