Python theorytheory 0/50 · 0%
Tooling · medium

23. Context managers and `with`

Deterministic setup/teardown using with statements.

The `with` statement ensures cleanup code runs even if an exception occurs, most commonly for files.

python
with open("data.txt") as f:
    contents = f.read()
# file is automatically closed here, even on error

You can build your own context manager with a class implementing `__enter__`/`__exit__`, or more simply with `contextlib.contextmanager`:

python
from contextlib import contextmanager

@contextmanager
def timer():
    import time
    start = time.time()
    yield
    print(f"took {time.time() - start:.3f}s")

with timer():
    total = sum(range(1_000_000))

Check your understanding

  1. 1. What guarantee does `with open(...) as f:` provide?

  2. 2. Which decorator turns a generator function into a context manager?

  3. 3. Which dunder methods does a class-based context manager need?