Context managers and the with statement
Course contents (15 lessons)
- Iteration the Python way
- List, dict and set comprehensions
- Iterators and generators
- Functions as building blocks
- Closures and decorators
- Context managers and the with statement
- Object-oriented Python in depth
- Classes and dataclasses
- Properties and special (dunder) methods
- Inheritance versus composition
- Quality: types, packaging and tests
- Type hints and mypy
- Packaging a project with pyproject.toml
- Testing with pytest
- Async code and web APIs
- async and await with asyncio
- Working with HTTP APIs and JSON
- Performance, concurrency and a final project
- Performance and profiling
- Concurrency: threads versus processes
- Final project: a price tracker command-line tool
The problem with statement solves
Many resources must be released: files, database connections, locks, temporary folders. If you forget, you leak them. If an error happens between acquiring and releasing, a naive version of the code skips the release. You could use try/finally every time, but that gets repetitive. The with statement packages the pattern.
with open("report.txt", "w", encoding="utf-8") as f:
f.write("done")
# the file is closed here, even if write() had raised an error
The protocol
An object works with with if it has two methods: __enter__, called at the start (its return value goes into the name after as), and __exit__, called at the end, always. Here is a context manager written as a class. It measures how long a block takes:
import time
class Stopwatch:
def __init__(self, label):
self.label = label
self.elapsed = 0.0
def __enter__(self):
self._start = time.perf_counter()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.elapsed = time.perf_counter() - self._start
print(f"{self.label}: {self.elapsed:.3f}s")
return False # do not swallow exceptions
with Stopwatch("sum of squares") as sw:
total = sum(i * i for i in range(2_000_000))
print(total)
print(sw.elapsed > 0) # True
What __exit__ receives
If the block finished normally, the three arguments are all None. If an exception was raised inside the block, they hold the exception type, the instance and the traceback. Returning a true value from __exit__ tells Python to swallow the exception. Returning False or None lets it continue upward. Swallowing exceptions by accident is a bug waiting to happen, so be deliberate. Forgetting a return is fine, since None is falsy and does the right thing.
The easier way: contextlib.contextmanager
Writing a class for each small case is heavy. The contextlib module lets you write a generator instead. Everything before yield is the setup. The yielded value goes after as. Everything after yield is the cleanup.
import os
import tempfile
from contextlib import contextmanager
@contextmanager
def working_directory(path):
previous = os.getcwd()
os.chdir(path)
try:
yield path
finally:
os.chdir(previous)
with working_directory(tempfile.gettempdir()):
print(os.getcwd())
print(os.getcwd()) # back where we started
The try/finally around yield is essential. If the block raises, the exception is thrown into the generator at the yield line. Without finally, the cleanup code would be skipped, which defeats the purpose. I have seen this mistake in real code more than once.
A practical example: a temporary database transaction
import sqlite3
from contextlib import contextmanager
@contextmanager
def transaction(connection):
try:
yield connection
connection.commit()
except Exception:
connection.rollback()
raise
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE items (name TEXT, qty INTEGER)")
with transaction(conn) as c:
c.execute("INSERT INTO items VALUES (?, ?)", ("pen", 10))
try:
with transaction(conn) as c:
c.execute("INSERT INTO items VALUES (?, ?)", ("ink", 5))
raise RuntimeError("something went wrong")
except RuntimeError:
pass
print(conn.execute("SELECT name FROM items").fetchall()) # [('pen',)]
On success the changes are committed. On an error they are rolled back and the exception is raised again, so the caller still knows. The failed insert of "ink" never reaches the table. Note that sqlite3 connections can act as context managers themselves, but they commit or roll back without closing. Writing your own makes the intent explicit.
Handy helpers in contextlib
suppress(FileNotFoundError)ignores a specific exception:with suppress(FileNotFoundError): os.remove(path).redirect_stdoutsendsprintoutput to another file object, which is useful in tests.ExitStacklets you enter a variable number of context managers, for example opening every file in a list.
from contextlib import ExitStack
paths = ["a.txt", "b.txt", "c.txt"]
with ExitStack() as stack:
files = [stack.enter_context(open(p, encoding="utf-8")) for p in paths]
# all files are closed together when the block ends
Several managers in one statement
You can open more than one at once: with open("in.txt") as src, open("out.txt", "w") as dst:. For long lists, wrap them in brackets over several lines. Python 3.10 and later allow that.
Common mistakes
- Using the object after the block. The file is closed; reading it raises
ValueError. - Missing try/finally in a generator-based manager. Explained above.
- Yielding more than once in a
@contextmanagerfunction. It must yield exactly once. - Doing real work in __exit__ that can itself fail, hiding the original exception.
Try it yourself
Write a context manager temporary_env(name, value) that sets an environment variable inside the block and restores the old value (or removes the variable) afterwards. Use contextlib.contextmanager. Test it by raising an exception inside the block and confirming the variable is still restored.
import time
class Stopwatch:
def __init__(self, label):
self.label = label
self.elapsed = 0.0
def __enter__(self):
self._start = time.perf_counter()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.elapsed = time.perf_counter() - self._start
print(f"{self.label}: {self.elapsed:.3f}s")
return False # do not swallow exceptions
with Stopwatch("sum of squares") as sw:
total = sum(i * i for i in range(2_000_000))
print(total)
print(sw.elapsed > 0) # True
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account