I\'d just like to exit out of a with statement under certain conditions:
with open(path) as f:
print \'before condition\'
if
Since break can only occur inside a loop your options are somewhat limited inside the with to:
Having a function and using return is probably the cleanest and easiest solution here if you can isolate the with and the associated statements (and nothing else) inside a function.
Otherwise generate an exception inside the with when needed, catch immediately below/outside the with to continue the rest of the code.
Update: As OP suggests in the comments below (perhaps tonuge in cheek?) one could also wrap the with statement inside a loop to get the break to work - though that would be semantically misleading. So while a working solution, probably not something that would be recommend).