← Back to Python, page 1

python-0008 · Medium mid

How do context managers and the with statement work? Write one with a class and one with contextlib.

A context manager defines setup and cleanup around a block: __enter__ runs at the start of with, and __exit__ runs at the end even if an exception occurs. contextlib.contextmanager builds one from a generator, with code before yield as setup and code after it, usually in a finally block, as cleanup. Files, locks and database transactions use this pattern.

Full answer
python
from contextlib import contextmanager

class Tag:
    def __init__(self, name): self.name = name
    def __enter__(self):
        print(f"<{self.name}>"); return self
    def __exit__(self, exc_type, exc, tb):
        print(f"</{self.name}> exception={exc_type.__name__ if exc_type else None}")
        return False

with Tag("p"):
    print("text")
try:
    with Tag("div"):
        raise ValueError("boom")
except ValueError as e:
    print("caught", e)

@contextmanager
def tag(name):
    print(f"<{name}>")
    try:
        yield
    finally:
        print(f"</{name}>")

with tag("span"):
    print("inside")

Output:

text
<p>
text
</p> exception=None
<div>
</div> exception=ValueError
caught boom
<span>
inside
</span>

The class version prints its enter and exit messages, and __exit__ receives the exception type when the block raises. Returning a false value from __exit__ lets the exception propagate, which is why the ValueError reaches the outer except.

The generator version does the same job with less code. The finally around yield matters: without it, an exception inside the block would skip the cleanup.

Uses beyond files:

  • threading.Lock() releases the lock automatically.
  • sqlite3 connections used in with commit or roll back the transaction.
  • contextlib.suppress(FileNotFoundError) ignores a specific exception.
  • contextlib.ExitStack manages a variable number of resources.
python
from contextlib import contextmanager

class Tag:
    def __init__(self, name): self.name = name
    def __enter__(self):
        print(f"<{self.name}>"); return self
    def __exit__(self, exc_type, exc, tb):
        print(f"</{self.name}> exception={exc_type.__name__ if exc_type else None}")
        return False

with Tag("p"):
    print("text")
try:
    with Tag("div"):
        raise ValueError("boom")
except ValueError as e:
    print("caught", e)

@contextmanager
def tag(name):
    print(f"<{name}>")
    try:
        yield
    finally:
        print(f"</{name}>")

with tag("span"):
    print("inside")

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • __enter__ and __exit__ wrap a block
  • __exit__ runs even on exceptions
  • A false return lets exceptions propagate
  • contextmanager builds one from a generator
  • Use finally around yield

Common mistakes

  • Forgetting finally in generator-based managers
  • Returning True from __exit__ and hiding errors

Follow-ups

  • What does ExitStack solve?
  • How does a sqlite3 connection behave as a context manager?

Tips

  • Mention exception handling in __exit__