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__() method performs any
necessary initialization, and returns a value.
.__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.
expression that evaluates to a context
If you provide a variable
in the optional part
as ”, that variable will be set to the value returned
by the context manager's
file class is a context manager; its
.__enter__() method returns the opened file,
.__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)
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
Starting in Python 2.7, you can enclose a block in multiple
context managers by repeating the “
” parts of the statement. For example:
with open('in') as inFile, open('out', 'w') as outFile: for rawLine in inFile: outFile.write(rawLine)