Context Managers
The with Statement
Master Python's context managers to safely manage resources: files, connections, and locks: all with automatic cleanup guaranteed.
What Is a Resource?
In programming, a resource is anything your program borrows from the operating system that must eventually be returned. If you forget to return it, bad things happen: memory leaks, locked files, or crashed databases.
The Problem Without with
Without context managers, you must manually open and close every resource. If an error occurs between open and close, the resource leaks:
The try/finally Fix
Python's try/finally block guarantees cleanup runs even if an exception occurs. But it's verbose and easy to get wrong:
The with Statement
A context manager is any object that defines how to set up and tear down a resource. The with statement is the syntax that activates it:
How with Works Under the Hood
The Context Manager Protocol
To be a context manager, an object must implement two magic methods. This is Python's "contract" for resource management:
with vs try/finally
How to Apply Context Managers
Example 1: Reading a File
Example 2: Writing to a File
Example 3: Custom Context Manager
Multiple Context Managers
You can nest or combine context managers. Python lets you use multiple with targets in a single statement, separated by commas:
The contextlib Shortcut
Writing a full class with __enter__ and __exit__ is verbose. Python's contextlib module provides a decorator that turns a generator function into a context manager:
Common Mistakes
Summary Comparison
| Manual close | try/finally | with statement | |
|---|---|---|---|
| Cleanup guaranteed? | No | Yes | Yes |
| Lines of code | 3+ | 5+ | 2 |
| Error-prone? | Very | Somewhat | No |
| Readable? | OK | Verbose | Excellent |
| Customizable? | No | Yes | Yes |
Question 1 of 5
What two methods must an object implement to be a context manager?
Question 2 of 5
What happens to the file f if an exception is raised inside this with block?
Question 3 of 5
In a @contextmanager decorated generator, which keyword separates the setup code from the cleanup code?
Question 4 of 5
What is the output of this code?
Question 5 of 5
Which of the following is the primary advantage of using a with statement over a try/finally block?