Lesson 11: Context Managers and the with Statement
Many programming tasks follow the same shape: set something up, use it, and then clean it up — open a file and close it, lock a resource and release it, start a database transaction and commit or roll it back. The cleanup step is easy to forget, and forgetting it causes leaks: files left open, locks never released, half-written data. A context manager is Python's answer. Used with the with statement, it guarantees the cleanup happens, even if the code in the middle raises an exception.
You have already used the most common context manager without noticing: with open(path) as f: closes the file when the block ends, however it ends. Behind the scenes, the object defines two special methods: __enter__, which runs when the with block starts, and __exit__, which runs when it ends. The example below builds a tiny timer this way — __enter__ records the start time, __exit__ prints how long the block took — and then uses it to time a small computation.
import time
class Timer:
def __enter__(self):
self.start = time.perf_counter()
return self
def __exit__(self, exc_type, exc_value, traceback):
elapsed = time.perf_counter() - self.start
print(f"block took {elapsed:.3f} seconds")
return False # do not swallow exceptions
with Timer():
total = sum(range(1_000_000))
print(total) # 499999500000
contextlib: the easy way to write one
Writing a class with __enter__ and __exit__ is the full-powered way to build a context manager, but for simple cases the standard library offers a shortcut. The contextlib module's @contextmanager decorator turns a generator function into a context manager: everything before the yield is the setup, the yielded value is what the as part receives, and everything after the yield is the cleanup, which runs even if the block raises. The timer above becomes a few lines, and the pattern is one you will reuse constantly — for example, to temporarily change a setting and restore it afterwards.
import time
from contextlib import contextmanager
@contextmanager
def timer():
start = time.perf_counter()
try:
yield
finally:
print(f"block took {time.perf_counter() - start:.3f} seconds")
with timer():
total = sum(range(1_000_000))
One detail in the class version deserves attention: __exit__ receives three arguments describing any exception that occurred, and if it returns a true value, the exception is swallowed. Returning False, as the timer does, means exceptions propagate normally — almost always what you want. Swallowing exceptions silently is the context-manager version of the bare except: from the last lesson, and it hides bugs in exactly the same way. Use a context manager whenever a resource needs guaranteed cleanup, and your programs will leak far less often.
Going further
A single with statement can manage several context managers at once: with open("a.txt") as a, open("b.txt") as b: opens two files and closes both when the block ends, in the reverse order they were opened. If opening the second file fails, the first is still closed properly — the cleanup guarantee holds for each manager independently. You can also nest with blocks inside each other when the logic is clearer that way. Either form is fine; the rule is simply that every resource that needs cleanup should be owned by a with block, not by your memory.
The contextlib module has two more helpers worth knowing. contextlib.suppress is a context manager that swallows a named exception inside its block — the tidy version of a try / except: pass that says exactly which exception you expect to ignore, and nothing else. contextlib.closing wraps an object that has a close() method but is not itself a context manager, so you can still use it with with. Both are small, but they remove the two most common reasons people write manual cleanup code.
A good exercise is to write a context manager that temporarily changes the working directory: on entry it records the current directory and moves somewhere else, and on exit it moves back, whatever happened in between. Test it by raising an exception inside the with block and checking that you still end up back in the original directory afterwards. That test — raising inside the block — is the one that proves the cleanup guarantee is real. It is also the test most people forget to write, which is why the guarantee is worth stating explicitly: the exit code runs even when the block fails, and that is the entire point of the pattern.
Key Terms
- Context manager
- An object that sets something up on entry and cleans it up on exit, used with the with statement.
- with statement
- The statement that enters a context manager, runs a block, and guarantees the exit code runs.
- __enter__
- The special method called when a with block starts; its return value is bound by as.
- __exit__
- The special method called when a with block ends, even if an exception occurred.
- contextlib
- A standard-library module with helpers for building context managers, including @contextmanager.
- @contextmanager
- A decorator that turns a generator function into a context manager: code before yield is setup, after yield is cleanup.
- Resource leak
- A resource such as an open file or lock that is never released, usually because cleanup was forgotten.
Discussion Questions
- What goes wrong if you open a file with open() and forget to close it? What if the code between open and close raises an exception?
- Why should __exit__ usually return False? When, if ever, would swallowing an exception be the right thing to do?
- Think of three resources in programs you write that need cleanup. Which ones already have a context manager in the standard library?
Practice Questions
- What guarantees does
with open(path) as f:give you? - What does
__enter__return, and where does that value go? - In the @contextmanager timer, what runs if the with block raises an exception?
- Write a context manager usage that times a loop — which form would you pick, class or @contextmanager?
- Why is returning True from
__exit__usually a mistake?
Show answers
- The file is closed when the block ends, even if an exception is raised. The file object's __exit__ closes it no matter how the block exits.
- Its return value is bound to the variable after as. In with Timer() as t:, t is whatever __enter__ returned.
- The code after yield, inside the finally. The exception propagates through the yield point, the finally runs, and the exception continues.
- Either works; @contextmanager is shorter for a simple timer. A class is better when the manager needs to carry state or be reused in complex ways.
- It swallows the exception silently. The caller never learns anything went wrong, hiding bugs just like a bare except: does.