Advanced Python: context managers and contextlib
Use with, __enter__, __exit__, contextmanager, suppress, and ExitStack in Python, with references and 20 exercises that include collapsible solutions.
Getting started
Home Assistant
Buying
Use with, __enter__, __exit__, contextmanager, suppress, and ExitStack in Python, with references and 20 exercises that include collapsible solutions.


AI-generated illustration
Some links on this page are affiliate links. The button opens Amazon so you can check today’s price.
The with statement guarantees that a resource (a file, a lock, a connection) is released cleanly, even if a block raises an exception. That is the context manager protocol. You can implement it as a class (__enter__ / __exit__) or in a functional style with contextlib.contextmanager and yield.
with and fileswith open("f.txt", encoding="utf-8") as f:
data = f.read()
# file closed here
__exit__ receives the exception type, its value, and the traceback. Returning True swallows the exception (rare, and worth documenting).
class CM:
def __enter__(self):
print("enter")
return self
def __exit__(self, exc_type, exc, tb):
print("exit")
contextlib.contextmanagerfrom contextlib import contextmanager
@contextmanager
def tag(name):
print("<", name, ">")
yield
print("</", name, ">")
The code before yield is the entry. The code after is the exit (like finally).
suppress, redirect_stdout, ExitStacksuppress(OSError): ignore the listed exceptions inside the block.ExitStack: open several context managers dynamically and close them in reverse order. Useful when the number of contexts varies.Exercise 1 — Use with open(...) to read README if it is present (ignore the error with try/except or Path.exists). Easy
from pathlib import Path
p = Path("README")
if p.exists():
with p.open(encoding="utf-8") as f:
print(f.read())
Exercise 2 — A Timer class that prints enter / exit with print. Easy
class Timer: def __enter__(self): print("enter") return self def __exit__(self, *a): print("exit")
with Timer(): pass
Exercise 3 — @contextmanager: a chdir(path) function that changes the current directory and then restores the old one (use os.chdir and try/finally in the generator). Easy
import os from contextlib import contextmanager
@contextmanager def chdir(path): old = os.getcwd() os.chdir(path) try: yield finally: os.chdir(old)
Exercise 4 — Use contextlib.suppress(FileNotFoundError) to try open("absent.txt"). Easy
from contextlib import suppress
with suppress(FileNotFoundError):
open("absent.txt")
Exercise 5 — What does __enter__ usually return, and what is that return value for? Easy
# The value bound to `as x`; often self, or an opened resource.
Exercise 6 — What is the difference between finally: and __exit__ in a context manager? Easy
# __exit__ can choose to suppress the exception; finally always runs after the block.
Exercise 7 — closing(thing) from contextlib: what is it for when an object has .close()? Easy
# Calls thing.close() when the with block exits, even if the object is not a native context manager.
Exercise 8 — Implement a context manager that counts how many times you have entered it (simple reentrancy with a counter). Intermediate
class Depth:
def __init__(self):
self.n = 0
def __enter__(self):
self.n += 1
return self
def __exit__(self, *a):
self.n -= 1
Exercise 9 — A contextmanager that temporarily adds a key to a dict and then removes it. Intermediate
from contextlib import contextmanager
@contextmanager def push(d, k, v): old = d.get(k, None) d[k] = v try: yield finally: if old is None: del d[k] else: d[k] = old
Exercise 10 — Use ExitStack to open two temporary files (or StringIO objects) in a single with. Intermediate
from contextlib import ExitStack from io import StringIO
with ExitStack() as stack: a = stack.enter_context(StringIO(“hi”)) b = stack.enter_context(StringIO(“yo”))
Exercise 11 — If __exit__ returns False, what happens to the exception? Intermediate
# It propagates after __exit__.
Exercise 12 — contextlib.redirect_stdout: redirect print to a StringIO. Intermediate
from contextlib import redirect_stdout
from io import StringIO
buf = StringIO()
with redirect_stdout(buf):
print("x")
print(buf.getvalue())
Exercise 13 — Why must yield in a contextmanager appear only once (in the usual case)? Intermediate
# The generator must stop at the first yield; otherwise you get a RuntimeError.
Exercise 14 — Write an atomic_write(path) context manager: write to a temporary file, then replace atomically (a sketch). Intermediate
import tempfile from pathlib import Path
@contextmanager def atomic_write(path: Path): fd, tmp = tempfile.mkstemp(dir=path.parent) try: with open(fd, “w”, encoding=“utf-8”, closefd=True) as f: yield f Path(tmp).replace(path) except Exception: Path(tmp).unlink(missing_ok=True) raise
Exercise 15 — An async context manager: name the protocol (__aenter__). This course does not cover it in detail, but look it up for asyncio. Hard
# __aenter__ / __aexit__; async with for asyncio resources.
Exercise 16 — nested (deprecated) versus ExitStack: why is ExitStack preferred? Hard
# A variable number of contexts, with a guaranteed close order.
Exercise 17 — contextlib.aclosing (3.10+) for async generators: one sentence on how you use it. Hard
# Ensures aclose() on an async generator, as closing() does for .close().
Exercise 18 — Test a @contextmanager that raises after yield. Does the exception reach the implicit finally? Hard
# Yes, the code after yield runs on the way out; exceptions are handled through GeneratorExit.
Exercise 19 — Implement nullcontext by hand (an object whose __enter__ returns the argument and whose __exit__ returns None). Hard
class NC:
def __init__(self, v=None):
self.v = v
def __enter__(self):
return self.v
def __exit__(self, *a):
pass
Exercise 20 — Why does with lock: work with a threading.Lock (which protocol)? Hard
# Lock implements __enter__ (acquire) and __exit__ (release).
asyncio: structured concurrency: async / await and the event loop.
Amazon.com (Python concurrent programming)
Was this page helpful?
Thank you!
What should we improve?
Torn between two models or stuck on a build? Drop us a line and we will get back to you by email.
Cookies and analytics
We use Google Analytics 4 to understand how the site is used (page views, navigation). It is only switched on if you accept. Declining does not stop you using the site. More: cookie settings and privacy policy (in French).