Skip to content

Module 17 · Advanced Python Concepts — topic 10 of 14

Context managers

Writing your own context managers: the __enter__/__exit__ protocol, handling exceptions in __exit__, contextlib.contextmanager, and handy standard managers such as suppress and redirect_stdout.

Beginner 10 min read·Lesson 256 of 306 in Python Programming

Learning objectives

  • Write class-based context managers
  • Write generator-based managers with contextlib
  • Use standard managers from contextlib

Definition

A context manager is an object that defines setup and cleanup for a with block through __enter__ and __exit__. contextlib.contextmanager lets a generator function act as one: code before yield is setup and code after it is cleanup.

Introduction

Files close themselves in a with block because they are context managers. You can give your own code the same guarantee: temporary settings, timers, transactions.

Why it matters

Context managers make 'always clean up' structural rather than something each caller must remember.

Detailed explanation

with obj as name: calls obj.__enter__() and binds its return value to name.

When the block ends, obj.__exit__(exc_type, exc, tb) runs. The arguments are None if no exception happened.

If __exit__ returns a true value, the exception is suppressed; returning False or None lets it propagate.

@contextlib.contextmanager turns a generator into a manager. Put cleanup in finally to make it run even on errors; catching the exception around yield lets you handle or suppress it.

contextlib.suppress(Error) ignores specific exceptions; redirect_stdout(buffer) captures printed output; ExitStack manages a variable number of managers.

Typical custom managers: temporarily changing state (indentation, directory, settings), timing blocks, and transactions that roll back on failure.

Keep __enter__ and __exit__ short; complex work belongs in normal methods.

A manager can be reused for many with blocks if it resets its state on entry, but generator-based managers are single-use: create a new one for each with statement.

Syntax

Python
from contextlib import contextmanager
@contextmanager
def managed():
print("setup")
try:
yield "resource"
finally:
print("cleanup")
  • __enter__ sets up, __exit__ cleans up.
  • Return True from __exit__ to suppress.
  • contextmanager for simple cases.

Code examples

A temporary indentation level

Python
class Indent:
level = 0
def __enter__(self):
Indent.level += 1
return self
def __exit__(self, *exc):
Indent.level -= 1
return False
def log(msg):
print(" " * Indent.level + msg)
log("start")
with Indent():
log("step 1")
with Indent():
log("detail")
log("step 2")
log("end")
Output
start
  step 1
    detail
  step 2
end

Standard helpers

Python
import io
from contextlib import redirect_stdout, suppress
buf = io.StringIO()
with redirect_stdout(buf):
print("captured!")
print("buffer has:", buf.getvalue().strip())
with suppress(KeyError):
{}["missing"]
print("KeyError suppressed")
Output
buffer has: captured!
KeyError suppressed

More examples

A transaction that rolls back

Python
import copy
from contextlib import contextmanager
@contextmanager
def transaction(data):
snapshot = copy.deepcopy(data)
try:
yield data
except Exception as e:
data.clear()
data.update(snapshot)
print(f"rolled back: {e}")
else:
print("committed")
accounts = {"A": 100, "B": 50}
with transaction(accounts) as acc:
acc["A"] -= 30
acc["B"] += 30
print(accounts)
with transaction(accounts) as acc:
acc["A"] -= 500
if acc["A"] < 0:
raise ValueError("insufficient funds in A")
acc["B"] += 500
print(accounts)
Output
committed
{'A': 70, 'B': 80}
rolled back: insufficient funds in A
{'A': 70, 'B': 80}

Step-by-step explanation

  • A snapshot is taken before the block runs.
  • If the block raises, the generator catches the exception at yield, restores the snapshot and does not re-raise, so the error is handled.
  • On success the else branch reports the commit and the changes stay.

Expected output

Running “A transaction that rolls back” prints exactly:

TextOutput
committed
{'A': 70, 'B': 80}
rolled back: insufficient funds in A
{'A': 70, 'B': 80}

Practical applications

  • Database transactions with sqlite3 connections.
  • Temporarily changing settings in tests.

Best practices

  • Use finally for cleanup in generator managers.
  • Suppress exceptions only deliberately.
  • Prefer contextlib helpers over custom code.

Common mistakes

Cleanup without finally

Avoid

@contextmanager
def opened(p):
f = open(p)
yield f
f.close() # skipped on error

Prefer

@contextmanager
def opened(p):
f = open(p, encoding="utf-8")
try:
yield f
finally:
f.close()

An exception in the block stops the generator at yield.

Important notes

  • Async code uses async with and __aenter__/__aexit__.

Key takeaways

  • __enter__/__exit__ define a context manager.
  • contextmanager turns generators into managers.
  • suppress, redirect_stdout and ExitStack are ready-made.

Try it yourself

  1. 1
    Write a context manager that changes the working directory and restores it afterwards.
  2. 2
    Write a timer context manager that stores the elapsed time on the object.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

2 questions test this exact topic. Answers and explanations are revealed after you submit.

  • AdvancedWhat is printed?
  • AdvancedWhat is printed?
Practise this topic