Context management with with

A more rational way to encapsulate the try-except-finally pattern is to use the keyword with and a context manager. Python defines context managers for things like accessing files and custom context managers. One advantage of context managers is that they can define cleanup actions that are always executed, regardless of whether an exception occurs or not.

Opening and closing files

The following list shows the opening and reading of a file using with and a context manager.

1filename = "myFile1.py"
2with open(filename, "r") as f:
3    for line in f:
4        print(f)

A context manager is set up here, which encloses the open() function and the subsequent block. The predefined clean-up action of the context manager closes the file, even if an exception occurs. As long as the expression in the first line is executed without triggering an exception, the file is always closed. This code is equivalent to this code:

1filename = "myfile1.py"
2try:
3    f = open(filename, "r")
4    for line in f:
5        print(line)
6except Exception as e:
7    raise e
8finally:
9    f.close()

See also

Locking

threading.Lock can be used with try-finally:

lock = threading.Lock()

try:
    print("a Job")
    print("another Job")
finally:
    lock.release()

However, using the context manager is more elegant:

with lock:
   print("a Job")
   print("another Job")

Suppressing exceptions

Context managers can also be used to suppress the output of Exceptions and continue execution.

try:
    os.remove("somefile.tmp")
except FileNotFoundError:
    pass

This can be written more elegantly as:

from contextlib import suppress

with suppress(FileNotFoundError):
    os.remove("somefile.tmp")