Search code examples
pythonwith-statement

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?)


Solution

  • This question was asked before Python 3.4 existed but with 3.4 you can use contextlib.supress, suppressing your own personal exception.

    See that this (runnable as is) code

    from contextlib import suppress
    
    class InterruptWithBlock(UserWarning):
        """To be used to interrupt the march of a with"""
    
    condition = True
    with suppress(InterruptWithBlock):
        print('before condition')
        if condition: raise InterruptWithBlock()
        print('after condition')
    
    # Will not print 'after condition` if condition is True.
    

    So with the code in the question, you'd do:

    with suppress(InterruptWithBlock) as _, open(path) as f:
        print('before condition')
        if <condition>: raise InterruptWithBlock()
        print('after condition')
    
    

    Note: If you're (still) before 3.4, you can still make your own suppress context manager easily.