Tutorials / Python: Intermediate to Advanced / Context managers and the with statement

Context managers and the with statement

13 min read python
Course contents (15 lessons)
  1. Iteration the Python way
  2. List, dict and set comprehensions
  3. Iterators and generators
  4. Functions as building blocks
  5. Closures and decorators
  6. Context managers and the with statement
  7. Object-oriented Python in depth
  8. Classes and dataclasses
  9. Properties and special (dunder) methods
  10. Inheritance versus composition
  11. Quality: types, packaging and tests
  12. Type hints and mypy
  13. Packaging a project with pyproject.toml
  14. Testing with pytest
  15. Async code and web APIs
  16. async and await with asyncio
  17. Working with HTTP APIs and JSON
  18. Performance, concurrency and a final project
  19. Performance and profiling
  20. Concurrency: threads versus processes
  21. 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_stdout sends print output to another file object, which is useful in tests.
  • ExitStack lets 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 @contextmanager function. 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.

python
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