Skip to the page

Functions and flow · core

The with statement and context managers

with calls enter first and always calls exit at the end, even when the block raises or returns. You can write a context manager as a class or with contextlib.contextmanager, and the cleanup after yield needs try/finally.

The notes

What you must know

  • enter runs first and its return value goes to as. exit(exc_type, exc, tb) always runs, also on an exception or return.
  • If exit returns True, the exception is swallowed. That is rarely what you want. A timer should return False.
  • @contextlib.contextmanager: code before yield is enter, code after it is exit. Without try/finally around the yield, cleanup is skipped when the block raises.
  • ExitStack handles a variable number of resources. Also suppress, nullcontext, closing and redirect_stdout.
  • Async: async with, aenter and aexit, asynccontextmanager.
  • time.perf_counter() is monotonic and precise for durations; time.time() can jump when the clock changes.
  • ContextDecorator makes a context manager usable as a decorator, but it reuses one instance for every call, so keep the start time in a local variable, not on self. The @contextmanager version makes a fresh generator per call.
  • Log with lazy arguments: logger.info("%s took %.1f ms", name, ms).

The red pen

Common traps: mistake → fix

  • Mistake: with catches exceptions

    Fix: it only guarantees exit runs; the exception continues unless exit returns True.

  • Mistake: Code after yield always runs

    Fix: only inside finally.

  • Mistake: time.time() is fine for timing

    Fix: it can go backwards; use perf_counter.

Easy to hard

Questions interviewers ask, easy to hard

  1. What does the with statement do?
  2. What happens when an exception is raised inside the block?
  3. How do you write your own context manager in two ways?
  4. Write timer(name) that logs the milliseconds even when the block raises.
  5. Why can ContextDecorator break with overlapping calls?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview