Created
March 4, 2014 19:42
-
-
Save tmr232/9354051 to your computer and use it in GitHub Desktop.
Loop Labels - Python hack for breaking out of nested loops.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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