I\'d just like to exit out of a with statement under certain conditions:
with open(path) as f:
print \'before condition\'
if
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 : 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.