What is the python “with” statement designed for?

Technology CommunityCategory: PythonWhat is the python “with” statement designed for?
VietMX Staff asked 3 years ago

The with statement simplifies exception handling by encapsulating common preparation and cleanup tasks in so-called context managers.

For instance, the open statement is a context manager in itself, which lets you open a file, keep it open as long as the execution is in the context of the with statement where you used it, and close it as soon as you leave the context, no matter whether you have left it because of an exception or during regular control flow.

As a result you could do something like:

with open("foo.txt") as foo_file:
    data = foo_file.read()

OR

from contextlib import nested
with nested(A(), B(), C()) as(X, Y, Z):
    do_something()

OR (Python 3.1)

with open('data') as input_file, open('result', 'w') as output_file:
    for line in input_file:
        output_file.write(parse(line))

OR

lock = threading.Lock()
with lock: #Critical section of code