Skip to main content
Albero Academy

Context Managers

The machinery behind with — guaranteed setup and teardown.

Advanced Python9 min

A context manager is the machinery behind the with statement: it runs setup code when the block is entered andguaranteed cleanup when it's exited — even if an exception is raised. That's why with open(...) always closes the file.

The two methods

A class becomes a context manager by defining __enter__ (setup, returns the resource) and __exit__ (teardown):

__enter__ / __exit__
class Timer:
def __enter__(self):
self.start = time.time()
return self # bound to 'as t'
def __exit__(self, exc_type, exc, tb):
print(f"took {time.time() - self.start:.3f}s")
# return False → exceptions propagate; True → suppress them
with Timer() as t:
do_work() # __exit__ runs afterwards, error or not

The easy way: @contextmanager

The contextlib decorator turns a generator into a context manager — code before yield is setup, after it is teardown:

@contextmanager
from contextlib import contextmanager
import time
@contextmanager
def timer():
start = time.time() # setup
try:
yield # the with-body runs here
finally:
print(f"took {time.time() - start:.3f}s") # teardown
with timer():
do_work()

Key takeaways

  1. 01A context manager guarantees setup on entry and cleanup on exit of a with block.
  2. 02__enter__ returns the resource; __exit__ handles teardown (and can suppress exceptions).
  3. 03@contextmanager + a generator (setup, yield, teardown) is the concise way to write one.
  4. 04They power files, locks, transactions and temporary state changes.
  5. 05Use one whenever you have a "do then always undo" pattern.

Finished this chapter?

Mark it complete to track your progress through Python.