jmilloy jmilloy - 4 months ago 9
Python Question

break or exit out of with statement?

I'd just like to exit out of a

with
statement under certain conditions:

with open(path) as f:
print 'before condition'
if <condition>: break #syntax error!
print 'after condition'


Of course, the above doesn't work. Is there a way to do this? (I know that I can invert the condition:
if not <condition>: print 'after condition'
-- any way that is like above?)

Answer

The best way would be to encapsulate it in a function and use return:

def do_it():
    with open(path) as f:
        print 'before condition'
        if <condition>:
            return
        print 'after condition'