Break or exit out of “with” statement?

后端 未结 12 2168
伪装坚强ぢ
伪装坚强ぢ 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 <condition>: 
                raise BreakOut #syntax error!
            print('after condition')
    except BreakOut:
        pass
    
    0 讨论(0)
  • 2020-12-02 11:49

    as shorthand snippet:

    class a:
        def __enter__(self):
            print 'enter'
        def __exit__(self ,type, value, traceback):
            print 'exit'
    
    for i in [1]:
        with a():
            print("before")
            break
            print("after")
    

    ...

    enter
    before
    exit
    
    0 讨论(0)
  • 2020-12-02 11:53
    f = open("somefile","r")
    for line in f.readlines():
           if somecondition: break;
    f.close()
    

    I dont think you can break out of the with... you need to use a loop...

    [edit] or just do the function method others mentioned

    0 讨论(0)
  • 2020-12-02 11:54

    Use while True:

    while True:
        with open(path) as f:
            print 'before condition'
            if <condition>: 
                break 
            print 'after condition n'
        break
    
    0 讨论(0)
  • 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 <condition>: 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.

    0 讨论(0)
  • 2020-12-02 11:57

    I think you should just restructure the logic:

    with open(path) as f:
        print 'before condition checked'
        if not <condition>:
            print 'after condition checked'
    
    0 讨论(0)
提交回复
热议问题