Break or exit out of “with” statement?

后端 未结 12 2223
伪装坚强ぢ
伪装坚强ぢ 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:42

    Here is another way of doing it using try and except, even though inverting the condition is probably more convenient.

    class BreakOut(Exception): pass
    
    try:
        with open(path) as f:
            print('before condition')
            if : 
                raise BreakOut #syntax error!
            print('after condition')
    except BreakOut:
        pass
    

提交回复
热议问题