12. keyword: with ... as vars

 

介紹

The with statement is used to wrap the execution of a block with methods defined by a context manager. (try...except...finally)

https://www.python.org/dev/peps/pep-0343/

The with statement guarantees that if the __enter__() method returns without an error, then __exit__() will always be called.

Thus, if an error occurs during the assignment to the target list, it will be treated the same as an error occurring within the suite would be.

寫法:

with expression [as variable]:
    with-block

 


with

with keyword is used when working with unmanaged resources

      with VAR = EXPR:
            BLOCK

相當於:

        VAR = EXPR
        VAR.__enter__()
        try:
            BLOCK
        finally:
            VAR.__exit__()

 

Example:

with open('output.txt', 'w') as f:
    f.write('Hi there!')

The advantage of using a with statement is that it is guaranteed to close the file no matter how the nested block exits.

If an exception occurs before the end of the block, it will close the file before the exception is caught by an outer exception handler.

If the nested block were to contain a return statement, or a continue or break statement,
the with statement would automatically close the file in those cases, too.

 

 

Context Manager(__enter__, __exit__)

    class controlled_execution:

        def __enter__(self):
            .................
            return something
            # 這裡的 something 又叫 context guard

        def __exit__(self, type, value, traceback):
            tear things down


    with controlled_execution() as mycg:
         some code

 

as

with open('output.txt', 'w') as f:
    f.write('Hi there!')

# 把 open('output.txt', 'w') 的 return 看成 f

 

傳播

如果 with 的 BLOCK 中沒有發生 exception, __exit__()依然會執行, 此時__exit__()的 type, value, traceback 都是 None

__exit__
    return False

若 return False, 則例外會被重新丟出, 否則例外就停止傳播

 

 

Creative Commons license icon Creative Commons license icon