Skip to content

Instantly share code, notes, and snippets.

@orez-
Created June 10, 2014 16:01
Show Gist options
  • Save orez-/bdfa0cdce9e6c4d0f6cf to your computer and use it in GitHub Desktop.
Save orez-/bdfa0cdce9e6c4d0f6cf to your computer and use it in GitHub Desktop.
Breakable 'with' block
# 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
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