Break or exit out of “with” statement?

后端 未结 12 2244
伪装坚强ぢ
伪装坚强ぢ 2020-12-02 11:04

I\'d just like to exit out of a with statement under certain conditions:

with open(path) as f:
    print \'before condition\'
    if 

        
12条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-02 11:56

    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.

提交回复
热议问题