Skip to content

Instantly share code, notes, and snippets.

@tmr232
Created March 4, 2014 19:42
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmr232/9354051 to your computer and use it in GitHub Desktop.
Save tmr232/9354051 to your computer and use it in GitHub Desktop.
Loop Labels - Python hack for breaking out of nested loops.
class LoopLabel(object):
def __init__(self):
super(LoopLabel, self).__init__()
class MyLoopLabel(Exception): pass
self._label_exception = MyLoopLabel
def __enter__(self):
return self._label_exception
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is self._label_exception:
return True
return False
# And usage:
with LoopLabel() as loop1:
for x in range(10):
print "x", x
for y in range(10):
print "y", y
if x > 2:
raise loop1()
if y > 2:
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment