Context Management

Learn about context managers that simplify resource management and ensure proper cleanup even with exceptions.

What are context managers?

The need to close files when we are finished with them can make our code quite ugly. Because an exception may occur at any time during file I/O, we ought to wrap all calls to a file in a try...finally clause. The file should be closed in the finally clause, regardless of whether I/O was successful. This isn’t very Pythonic. Of course, there is a more elegant way to do it.

Python’s file objects are also context managers. By using the with statement, the context management methods ensure that the file is closed, even if an exception is raised. By using the with statement, we no longer have to explicitly manage the closing of the file.

Press + to interact
Context managers in Python
Context managers in Python

Here is what a file-oriented with statement looks like in practice:

Press + to interact
source_path = Path("requirements.txt")
with source_path.open() as source_file:
for line in source_file:
print(line, end = '')

The open method of a Path object returns a file object, which has __enter__() and __exit__() methods. The returned object is assigned to the variable named source_file by the as clause. We know the file will be closed when the code returns to the outer indentation level, and that this will happen even if an exception is raised.

The with statement is used widely, often where startup and cleanup code need to be connected in spite of anything that might go wrong. For example, the urlopen call returns a context object that can be used in a with ...

Get hands-on with 1400+ tech skills courses.