Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 10 / Topic 10 of 11

Context managers

A context manager is an object used with with that runs setup code at the start of the block and clean-up code at the end, even if an error happens. You already use one: with open(...) as f: closes the file for you (Part 8). Think of a hotel key card: you get it at check-in, and it is always deactivated at check-out, however your stay went.

Writing one with a class

  • __enter__(self) runs at the start. What it returns goes into as name.
  • __exit__(self, exc_type, exc_value, traceback) runs at the end. The three arguments describe the error, or are all None if there was none. Return False so errors are not hidden.

Real-world example: time a block of code.

import time

class Timer:
    def __init__(self, label):
        self.label = label

    def __enter__(self):
        self.start = time.perf_counter()
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        print(f"[{self.label}] took {time.perf_counter() - self.start:.1f}s")
        return False

with Timer("backup"):
    time.sleep(0.3)

Output (time varies a little):

[backup] took 0.3s

Writing one with @contextmanager

contextlib.contextmanager turns a generator into a context manager. Code before yield is the setup, the yielded value goes into as, and code after yield (in finally) is the clean-up.

Real-world example: work inside a folder for a moment, then always go back.

import os
import tempfile
from contextlib import contextmanager
from pathlib import Path

@contextmanager
def change_dir(folder):
    old = Path.cwd()
    os.chdir(folder)
    try:
        yield
    finally:
        os.chdir(old)           # runs even if the block raises an error

start = Path.cwd()
with tempfile.TemporaryDirectory() as temp:     # built-in: makes and deletes a folder
    with change_dir(temp):
        Path("demo_report.txt").write_text("ok", encoding="utf-8")
        print(os.listdir("."))  # ['demo_report.txt']
print(Path.cwd() == start)      # True

tempfile.TemporaryDirectory() is itself a context manager: it creates an empty folder and deletes it (and its files) at the end of the block.

Real-world example: a resource that always closes.

from contextlib import contextmanager

@contextmanager
def open_connection(name):
    print("open", name)
    try:
        yield name
    finally:
        print("close", name)

try:
    with open_connection("payments-db") as conn:
        print("using", conn)
        raise ValueError("bad amount")
except ValueError as error:
    print("error:", error)

Output:

open payments-db
using payments-db
close payments-db
error: bad amount

๐Ÿ” Going deeper: one with can hold several managers: with open(a) as src, open(b, "w") as dst:. contextlib.suppress(FileNotFoundError) is a ready-made manager that ignores one error type.

Full program: examples/06_context_managers.py.

Read more: the official contextlib documentation.

Done here? The practice set for Part 10 โ€” 8 exercises with solutions โ€” is on the part page.

Search the guide