What Is a Context Manager in Python?
Learn what a Python context manager is, how __enter__ and __exit__ work with the with statement, and how contextlib.contextmanager simplifies it.
Expected Interview Answer
A context manager is an object that defines setup and teardown behavior around a block of code using the `with` statement, guaranteeing cleanup (like closing a file) even if an error occurs.
It implements `__enter__`, which runs at the start of the `with` block and returns a value bound by `as`, and `__exit__`, which runs at the end and receives any exception info, allowing it to suppress or clean up after errors. Files, locks, and database connections commonly use this pattern so resources are always released. You can also build one quickly with the `contextlib.contextmanager` decorator on a generator function that yields once.
- Guarantees cleanup even when exceptions occur
- Reduces boilerplate compared to manual try/finally
- Makes resource lifetimes explicit and scoped
- contextlib.contextmanager avoids writing a full class
- Widely used for files, locks, and connections
AI Mentor Explanation
A context manager is like the ritual around a drinks break: __enter__ is the umpire signalling the break to start and the players jogging off, and __exit__ is them jogging back on and the umpire restarting the clock, guaranteed to happen even if rain briefly interrupts the break itself. The `with` block is simply everything that happens during that bounded interval.
Step-by-Step Explanation
Step 1
__enter__ runs first
Called when the with block starts; its return value binds to the `as` variable.
Step 2
Block body executes
The indented code under `with` runs, possibly raising an exception.
Step 3
__exit__ runs last
Called on exit with exception type, value, and traceback (or None, None, None on success).
Step 4
Suppressing errors
Returning True from __exit__ suppresses the exception; returning False/None lets it propagate.
Step 5
Shortcut with contextlib
@contextlib.contextmanager turns a generator with one yield into a context manager without writing a class.
What Interviewer Expects
- Names __enter__ and __exit__ as the required dunder methods
- Knows the with statement guarantees cleanup on exception
- Understands __exit__'s exception-type/value/traceback parameters
- Knows about contextlib.contextmanager as a simpler alternative
- Can give a real example like file handling or locks
Common Mistakes
- Thinking with is just syntactic sugar for try/finally with no extra behavior
- Forgetting __exit__ can suppress exceptions by returning True
- Not knowing contextlib.contextmanager exists
- Confusing context managers with decorators
Best Answer (HR Friendly)
“A context manager automatically handles setup and cleanup around a block of code using Python's `with` statement — for example, automatically closing a file after you're done reading it, even if something goes wrong while reading.”
Code Example
from contextlib import contextmanager
@contextmanager
def timer(label):
import time
start = time.time()
try:
yield
finally:
print(f"{label} took {time.time() - start:.3f}s")
with timer("data load"):
data = [x * x for x in range(1_000_000)]Follow-up Questions
- What parameters does __exit__ receive and what does returning True do?
- How does contextlib.contextmanager work under the hood?
- Can you nest multiple context managers in one with statement?
- What's the difference between a context manager and a decorator?
- How would you write a context manager for a database transaction?
MCQ Practice
1. Which two methods must an object implement to be a context manager?
Context managers implement __enter__ for setup and __exit__ for teardown.
2. What does returning True from __exit__ do?
Returning True from __exit__ tells Python to suppress the exception rather than propagate it.
3. Which decorator turns a generator into a context manager?
contextlib.contextmanager wraps a generator function with a single yield into a context manager.
Flash Cards
What two methods define a context manager? — __enter__ (setup) and __exit__ (teardown).
What triggers __exit__? — The end of the with block, whether normal or via exception.
How to suppress an exception in __exit__? — Return True from __exit__.
Simplest way to write a context manager? — Use @contextlib.contextmanager on a generator with one yield.