
The with statement is used to wrap the execution of a block with methods defined by a context manager. This allows common try...except...finally usage patterns to be encapsulated for convenient reuse.
|
How does with statement works?
When execuating a with statment, an object called Context managers are normally invoked.
The context manager handles the entry into, and the exit from, the desired runtime context for the execution of the block of code.
-
The context expression (the expression given in the with_item) is evaluated to obtain a context manager.
-
The context manager’s
__exit__()is loaded for later use. -
The context manager’s
__enter__()method is invoked. -
If a target was included in the with statement, the return value from
__enter__()is assigned to it. -
The context manager’s
__exit__()method is invoked. If an exception caused the suite to be exited, its type, value, and traceback are passed as arguments to__exit__(). Otherwise, three None arguments are supplied.
|
The with statement guarantees that if the __enter__() method returns without an error, then __exit__() will always be called.




近期评论