How do __enter__ and __exit__ support context managers?
PICTURE THIS: HOW TO EXPLAIN IT
Simple meaning
__enter__ runs at the start of a with block and its return value is bound to as.
WHY — Dunder Methods instead of guessing?
Why interviewers care about Dunder Methods:
question about Dunder Methods.
trade-offs, and what you would actually do on a Python project - not buzzwords.
Name the idea, why it exists, then one short example.
End with when you use it and one common pitfall.
STEPS — What happens step by step?
Before you speak the answer, walk the interviewer through these steps:
- 1__enter__ runs at the
start of a with block and its return value is bound to as.
- 2__exit__ receives exception info
and returns a true value to suppress the exception.
- 3contextlib.contextmanager lets you write
the same protocol with a generator instead of a class.
- 4Give an example
One tiny concrete case you can say aloud.
- 5Common mistake
What juniors usually get wrong.
- 6Close
When you pick this over the alternative.
EXAMPLE — See it in action
Here's a short line you can speak, broken into clear beats:
Note: Adapt this scaffold to your own project — keep it under 60–90 seconds.
Key takeaway
__enter__ runs at the start of a with block and its return value is bound to as. __exit__ receives exception info and returns a true value to suppress the exception.