I\'d just like to exit out of a with
statement under certain conditions:
with open(path) as f:
print \'before condition\'
if
Here is another way of doing it using try
and except
, even though inverting the condition is probably more convenient.
class BreakOut(Exception): pass
try:
with open(path) as f:
print('before condition')
if <condition>:
raise BreakOut #syntax error!
print('after condition')
except BreakOut:
pass
as shorthand snippet:
class a:
def __enter__(self):
print 'enter'
def __exit__(self ,type, value, traceback):
print 'exit'
for i in [1]:
with a():
print("before")
break
print("after")
...
enter
before
exit
f = open("somefile","r")
for line in f.readlines():
if somecondition: break;
f.close()
I dont think you can break out of the with... you need to use a loop...
[edit] or just do the function method others mentioned
Use while True
:
while True:
with open(path) as f:
print 'before condition'
if <condition>:
break
print 'after condition n'
break
This is an ancient question, but this is an application for the handy "breakable scope" idiom. Just imbed your with
statement inside:
for _ in (True,):
with open(path) as f:
print 'before condition'
if <condition>: break
print 'after condition'
This idiom creates a "loop", always executed exactly once, for the sole purpose of enclosing a block of code inside a scope that can be broken out of conditionally. In OP's case, it was a context manager invocation to be enclosed, but it could be any bounded sequence of statements that may require conditional escape.
The accepted answer is fine, but this technique does the same thing without needing to create a function, which is not always convenient or desired.
I think you should just restructure the logic:
with open(path) as f:
print 'before condition checked'
if not <condition>:
print 'after condition checked'