The purpose of this statement is to protect a block of code with a context manager that insures that certain initialization and cleanup steps get performed, regardless of whether that block raises an exception.
A context manager is a class that has .__enter__() and .__exit__() methods.
The .__enter__() method performs any
necessary initialization, and returns a value.
The .__exit__() method is always executed
to perform necessary cleanup actions.
Starting with version 2.6, Python now was a with statement that executes a block using a context manager.
Here is the general form, where is the block to be executed.
B
withE[ asV]:B
is an
expression that evaluates to a context
manager.
E
If you provide a variable in the optional part
“Vas ”, that variable will be set to the value returned
by the context manager's V.__enter__()
method.
Python's file class is a context manager; its
.__enter__() method returns the opened file,
and its .__exit__() method closes the file.
For example, suppose you want to call a function beat() and pass it an opened file named "goat", but you want to be sure the file is closed
even if the beat() function raises an
exception. This code would do that:
with open("goat") as inFile:
beat(inFile)
When the beat() function terminates (either
normally or because it raised an exception), the file will be
closed (in the file.__exit__() method). If the
function raised an exception, that exception will then be
re-raised.
Starting in Python 2.7, you can enclose a block in multiple
context managers by repeating the “” parts of the statement. For example:
E[ as V
with open('in') as inFile, open('out', 'w') as outFile:
for rawLine in inFile:
outFile.write(rawLine)