Python context managers: how with works, and how to write your own
What the with statement guarantees, __enter__ and __exit__ step by step, the contextlib shortcut, and why returning True from __exit__ silently swallows errors.
Every Python developer writes with open(...) as f: in their first week. Fewer know what it
actually guarantees, or how to give their own classes the same superpower. It's a small feature
that prevents a whole class of bugs: files left open, locks never released, database connections
leaking until the server falls over.
What with guarantees
with open("report.txt", "w") as f:
f.write(build_report())Whatever happens inside the block (normal finish, return, an exception), the file is closed
afterwards. It's equivalent to:
f = open("report.txt", "w")
try:
f.write(build_report())
finally:
f.close()…but shorter, and impossible to get subtly wrong.
The protocol: enter and exit
Any object with these two methods works with with:
import sqlite3
class EventStore:
def __init__(self, path=":memory:"):
self.conn = sqlite3.connect(path)
def __enter__(self):
return self # this is what "as store" receives
def __exit__(self, exc_type, exc, tb):
self.conn.close() # always runs
# returning None means: don't hide exceptions
with EventStore("events.db") as store:
store.add(event)__exit__ gets the exception's type, value and traceback if the block failed, or three Nones if
it didn't. This is the store you build in the tracking service on the
Python Developer career path.
The trap: returning True
If __exit__ returns a true value, Python treats the exception as handled and carries on
after the block:
def __exit__(self, exc_type, exc, tb):
self.conn.close()
return True # every error inside the block now disappearsA typo, a failed insert, a KeyError: all silently swallowed. Only do this in a context manager
whose whole purpose is suppressing one specific exception, like contextlib.suppress.
The shortcut: contextlib.contextmanager
For simple cases, a generator with one yield is enough:
from contextlib import contextmanager
import time
@contextmanager
def timer(label):
start = time.perf_counter()
try:
yield
finally:
print(f"{label}: {time.perf_counter() - start:.3f}s")
with timer("planning"):
plan(vans, deliveries)Everything before yield is setup, everything after is cleanup. The try / finally matters:
without it, an exception in the block skips the cleanup. (New to yield? See
generators and iterators.)
Built-in context managers worth knowing
open()for files, andsqlite3connections (note:with conn:commits or rolls back a transaction but doesn't close the connection).threading.Lock(): acquire and always release.contextlib.suppress(FileNotFoundError): ignore one specific, expected error.tempfile.TemporaryDirectory(): a folder that deletes itself.unittest.mock.patch(...): replace something for the duration of a test.
When to write one
Whenever something must be undone after use: a connection closed, a lock released, a
temporary setting restored, a timer stopped. If you catch yourself writing try / finally with
the same cleanup in several places, that's a context manager waiting to be written.
Questions and answers
- What does the with statement do in Python?
- It runs setup code, then your block, then cleanup code, and guarantees the cleanup runs even if the block raises an exception or returns early. Files, locks and database connections use it so they're always closed or released.
- What happens if __exit__ returns True?
- The exception raised inside the with block is suppressed: execution continues after the block as if nothing went wrong. That's rarely what you want, so __exit__ should normally return None or False.
Practise it
Read next
- Python generators and iterators, explained with real examples
How iteration works under the hood, how yield turns a function into a lazy generator, how pipelines process files bigger than memory, and the exhaustion trap that catches everyone.
- SQL injection in Python: why f-strings break your queries (with sqlite3)
How building SQL with f-strings crashes on a name like 's-Hertogenbosch and lets attackers rewrite your query, and how parameterised queries in sqlite3 fix both.
- Reading files and CSV in Python: paths, encodings and DictReader
Open files safely with pathlib and with, choose the right encoding, handle Excel's byte order mark and decimal commas, and read CSV exports with csv.DictReader.