I recently read this question which had a solution about labeling loops in Java.
I am wondering if such a loop-naming system exists in Python. I have been in a situa
Here's a way to break out of multiple, nested blocks using a context manager:
import contextlib
@contextlib.contextmanager
def 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