Created
June 10, 2014 16:01
-
-
Save orez-/bdfa0cdce9e6c4d0f6cf to your computer and use it in GitHub Desktop.
Breakable 'with' block
This file contains 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
# http://stackoverflow.com/questions/11195140/python-break-or-exit-out-of-with-statement/23665658#23665658 | |
class fragile(object): | |
class Break(Exception): | |
"""Break out of the with statement""" | |
def __init__(self, value): | |
self.value = value | |
def __enter__(self): | |
return self.value.__enter__() | |
def __exit__(self, etype, value, traceback): | |
error = self.value.__exit__(etype, value, traceback) | |
if etype == self.Break: | |
return True | |
return error |
This file contains 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
from breakable_with import fragile | |
with fragile(open(path)) as f: | |
print 'before condition' | |
if condition: | |
raise fragile.Break | |
print 'after condition' | |
with fragile(open(path1)) as f: | |
with fragile(open(path2)) as g: | |
print f.read() | |
print g.read() | |
raise fragile.Break | |
print "This wont happen" | |
print "This will though!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment