Skip to the solution
MediumDSA14 min read

What is a context manager?

179 views

The problem

Question presented to candidate: "You write with open(path) as f: all the time. What is actually going on there? Explain what a context manager is, how you would write your own, and what happens when the code inside the block raises."

What a strong answer should cover:

  • A context manager is an object that sets something up on entry and is guaranteed to tear it down on exit; the with statement drives it, and it is a structured replacement for try/finally.
  • The protocol: __enter__() runs first and its return value is what as binds; __exit__(exc_type, exc_value, traceback) always runs, on normal exit, return, break or an exception.
  • Exception handling: __exit__ receives the exception, and a truthy return value suppresses it; returning None/False lets it propagate.
  • Two ways to write one: a class with __enter__/__exit__, or a generator decorated with contextlib.contextmanager (the code after yield must sit in finally to run on errors).
  • Real uses and stdlib helpers: files, locks, transactions, temporary state; contextlib.suppress, nullcontext, closing, ExitStack, plus async with for async managers.
  • A CPython detail: __enter__/__exit__ are looked up on the type, not the instance, and in 3.11 the bytecode is BEFORE_WITH plus WITH_EXCEPT_START.

Code / implementation expected: Yes โ€” a small class-based manager and the same thing written with @contextmanager, showing what happens when the body raises.

  • context-manager

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

14 min read ยท 13 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonA class-based context manager through every exit path
Python@contextmanager, the missing finally bug, and contextlib helpers

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 104 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

What is a generator's lifecycle?

Continue
What is a context manager? | Interview Question โ€” DevPrep