Concept Explanation
Resource management is a design pattern: acquire a resource, use it, then guarantee it is released — even if the code in the middle raises. Python's answer is the context manager, used with with.
with open("report.txt") as f:
data = f.read()
# the file is closed here, even if read() raised
The __enter__/__exit__ Contract
Any object with these two methods can be used with with:
class ManagedFile:
def __init__(self, name):
self.name = name
def __enter__(self):
self.file = open(self.name)
return self.file
def __exit__(self, exc_type, exc_value, traceback):
self.file.close()
return False # let the exception propagate
__exit__ decides whether to swallow the exception: return True to suppress it, False to let it propagate. The three parameters (exc_type, exc_value, traceback) are the exception — all None if no exception occurred.
contextlib.contextmanager
Most context managers are a try/finally in disguise, and @contextmanager lets you write one as a generator:
from contextlib import contextmanager
@contextmanager
def managed_file(name):
try:
f = open(name)
yield f # this is what the with-statement body sees
finally:
f.close()
The yield is where the body executes. Any code between the @ and the yield is "acquire"; after yield is "release". If the body raises, the exception is thrown back into the generator at the yield, so the finally still runs.
The "If a with-block" Comparison
A context manager that conditionally changes behaviour is useful when you want to temporarily change global state:
with redirect_stdout(io.StringIO()) as buf:
print("captured!")
with suppress(FileNotFoundError):
open("missing.txt")
ExitStack: Compose Multiple
contextlib.ExitStack lets you manage a dynamic number of resources in one block, and is the tool for "either one or many":
with ExitStack() as stack:
files = [stack.enter_context(open(name)) for name in names]
# handles each file as needed
This is also how you enter a context manager conditionally — stack.enter_context decides at runtime.
Why This Is a Pattern, Not a Trick
Cleanup is required by the type of problem, and a context manager is a reusable recipe for that problem. It is the Pythonic version of "resource acquisition is initialization", applied to files, locks, network connections, and — crucially — the implementation of your own rollback.
Code Example #1 (Basic)
From explicit try/finally to a reusable manager, and the return value of __exit__.
import time
from contextlib import contextmanager
# --- The naive way ---
def read_naive(filename):
f = open(filename)
try:
return f.read()
finally:
f.close()
# --- A hand-written class ---
class ManagedFile:
def __init__(self, name):
self.name = name
def __enter__(self):
print(f" opening {self.name}")
self.file = open(self.name)
return self.file
def __exit__(self, exc_type, exc_value, traceback):
print(f" closing {self.name}")
self.file.close()
if exc_type is not None:
print(f" body raised {exc_type.__name__}; cleanup still ran")
return False # propagate
# Write a file first so there is something to open
with open("sample.txt", "w") as setup:
setup.write("hello world")
with ManagedFile("sample.txt") as f:
print(f" read: {f.read()!r}")
print("done -- and the close happened even if read() had raised\n")
# --- The generator form ---
@contextmanager
def timing(label):
start = time.perf_counter()
try:
yield
finally:
print(f" {label} took {time.perf_counter() - start:.3f}s")
with timing("whole block"):
time.sleep(0.05)
print(" inside the timing block")
# --- Suppressing an exception deliberately ---
class IgnoreError:
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
if exc_type is ValueError:
print(" I swallowed the ValueError")
return True # True = suppress
return False
with IgnoreError():
raise ValueError("boom")
print(" we got past the block (ValueError was swallowed)\n")
The value of __exit__ details the pattern's contract: return True to suppress, and be deliberate about it. The naive file open also shows the trade-off — the try/finally works, but it is not reusable; a new context manager per cleanup problem is the pattern's pay-off.
Code Example #2 (Intermediate)
A transaction manager with rollback, plus ExitStack for dynamic resources.
import io
from contextlib import ExitStack, contextmanager, redirect_stdout, suppress
# ---------- A fake DB with a rollback-able transaction ----------
class FakeDB:
def __init__(self):
self.rows = []
self._journal = []
def insert(self, row):
self.rows.append(row)
self._journal.append(("insert", row))
def rollback(self):
for action, row in reversed(self._journal):
if action == "insert":
self.rows.remove(row)
self._journal.clear()
def __enter__(self):
self._journal.clear()
return self
def __exit__(self, exc_type, exc_value, traceback):
if exc_type is not None:
print(f" rolling back because: {exc_value}")
self.rollback()
return True # swallow the error after rollback
print(" commit")
return False
with FakeDB() as db:
db.insert(("alice", 100))
db.insert(("bob", 200))
raise ValueError("a bad row slipped in")
# rollback ran, and the exception was swallowed
print(f" rows after rollback: {db.rows}\n")
# ---------- Entering many resources with ExitStack ----------
@contextmanager
def named_resource(label):
print(f" entering {label}")
yield label
print(f" exiting {label}")
with ExitStack() as stack:
# We don't know how many resources we'll need until runtime
resource_names = ["mail", "cache", "queue"]
entered = [stack.enter_context(named_resource(r)) for r in resource_names]
print(f" operating on {entered}\n")
# ---------- Entering a context manager conditionally ----------
def maybe_verbose(openit, *names):
stack = ExitStack()
for name in names:
if openit:
stack.enter_context(named_resource(name))
return stack
with maybe_verbose(True, "a", "b") as st:
print(" conditionally entered two resources")
print(" they closed on the way out\n")
# ---------- contextlib utilities ----------
buf = io.StringIO()
with redirect_stdout(buf):
print("this is captured")
print("captured:", buf.getvalue().strip())
with suppress(FileNotFoundError):
open("does-not-exist.txt")
print("suppress: FileNotFoundError was swallowed\n")
# ---------- A manager that returns a value with cleanup ----------
@contextmanager
def db_session(db):
"""Give the body a database and always roll back on error."""
try:
yield db
except Exception:
db.rollback()
print(" rolled back")
raise
else:
print(" committed")
with db_session(FakeDB()) as session:
session.insert(("carol", 300))
print(" session closed cleanly\n")
ExitStack is the piece people discover too late. "Use a with, but the number of files depends on the input" is exactly the case it solves, and it also gives you a single place to manage cleanup when the with-block is dynamic or you enter resources conditionally.
Common Mistakes
- Forgetting the
finallywhen hand-writing the generator form: if you do not put the release code afteryieldin atry/finally, an exception in the body skips cleanup. - Returning
Truefrom__exit__by accident: it swallows exceptions. ReturnFalse(or nothing) to propagate. - Putting the body outside
yield'stry: exceptions leak past the release code. - Reusing a one-shot context manager: a
@contextmanagergenerator is single-use. Create a new one perwith. - Opening the resource before the manager's
__enter__, then assuming thewithcloses it: only files opened inside the manager get closed automatically. - Not using
ExitStackwhen the number of resources is dynamic: a manually-maintained list of cleanup calls is a bug waiting to leak. - Using
withon a lock and then locking again in the same thread (e.g.threading.Lockis not reentrant): usethreading.RLockif you need that. - Ignoring
exc_typein__exit__: it's how you know if the body raised; not checking leads to wrong rollback decisions. - Swallowing
KeyboardInterruptorSystemExit: your__exit__should re-raise those (they derive fromBaseException). - Blocking the body with a call that does not use the resource, but expecting the cleanup to happen: the
withdoesn't magically close anything; it only calls your__exit__.
Best Practices
- Use
@contextmanagerfor most cases, and a class only when you need custom__enter__and__exit__semantics. - Do the release in a
finally, and let exceptions propagate by choosingreturn False. - Only swallow the exception you expect — check
exc_type, and never swallowKeyboardInterruptorSystemExit. - Keep the resource acquisition inside
__enter__, not before it. - Use
ExitStackfor a dynamic number of resources — it is the cleanest way to enter several in one block. - Return the resource from
__enter__: many consumers want the opened handle. - Use the standard-library helpers
contextlib.suppress,redirect_stdout,closing. - Name the context manager at the point of use so readers understand what resource it owns.
- Use
yieldin a generator body to break the "acquire/use/release" into two phases. - Never rely on the
withto clean up a resource if you did not enter it through the manager.
Practice Exercises
- The Rollback Manager: Write a
FakeDBtransaction manager where__exit__rolls back on any exception and commits otherwise. Show both cases. - The Generator Manager: Reimplement the same
transactionusing@contextmanagerandyield, in atry/finallywhere the release is afinally. - The ExitStack: Read five filenames from a list, enter them all with
ExitStack(or a dynamic count), and print the order they close in.