Lesson · Python Data Model & Special Methods
Context Manager Protocol
70 min readContext Manager Protocol
The context manager protocol wraps a block with reliable setup and cleanup. `with` is Python's standard tool for resources that must be released even when exceptions occur.
Learning goals
- Explain the
withprotocol: evaluate the expression, run__enter__, execute the body, then run__exit__on every exit path. - Read
__exit__'s three exception arguments and predict what happens when the method returnsTrueversusFalse. - Write a class that times a block by storing a start reading in
__enter__and computing elapsed time in__exit__. - Explain the guarantee the protocol adds over writing setup and cleanup directly around the same code.
- Convert a simple class-based manager into
@contextlib.contextmanagerform and back.
Mental model
The protocol is a three-step flow around the body: __enter__ runs first and its return value is what as binds, the body runs next, and __exit__ runs last on every path. The three arguments describe the exception that ended the block, or are all None for a clean exit; the method's return value decides the exception's fate, because a truthy result suppresses it and False lets it keep travelling. The worked example's Timer.__exit__ returns False, so it measures without interfering.
Enter, body, exit, always in that order
the exit return value decides the exception's fate
Mental model
the same mechanism as a compact list
with EXPR as TARGET: EXPR.__enter__() runs, its return value binds to TARGET body if the body raises, the exception travels to __exit__ exit __exit__(exc_type, exc, tb); truthy suppresses, falsy re-raises
Core idea
with is sugar over a two-method protocol: __enter__ prepares and hands back the object bound by as, and __exit__ always runs afterwards, receiving the exception details when the body failed. The return value of __exit__ is the only decision point: falsy results re-raise any exception, truthy results swallow it. The worked example's Timer uses the pair as brackets around a measurement, which is the point of the protocol: cleanup that cannot be skipped, even by return or an exception.
__enter__
__enter__ runs when a with block begins and returns the value bound by as, if any.
__exit__
__exit__ runs when a with block leaves, including through an exception. Returning a truthy value indicates that the context manager handled and suppressed the exception.
Resource acquisition/release
A context manager owns a resource across a block: it acquires or prepares the resource in __enter__ and releases or finalizes it in __exit__, so both halves live in one object. The worked example's Timer takes the clock reading in __enter__ and computes the elapsed time in __exit__, with return False letting any exception keep travelling. The pattern guarantees release on every exit path: normal completion, return, or exception.
Exception handling in context managers
Context managers make setup and cleanup visible in control flow. Prefer them for resources whose release must happen even when an exception interrupts the body.
contextlib
contextlib is the standard-library module for building and composing context managers without writing a class. @contextlib.contextmanager turns a generator function into a context manager: code before yield acts as __enter__, the yielded value is what as binds, and code after yield runs when the block ends, with any body exception thrown in at the yield point. Ready-made managers such as contextlib.suppress cover common cases, and @contextmanager is the shorter form for managers that fit in one function.
Walkthrough
Timer.__enter__readstime.perf_counter()intoself.startand returnsself, which is whywith Timer() as timerbinds the timer instance itself totimer.- The body calls
sum(range(100_000)); the result is discarded, and the call only exists to give the timer something measurable to bracket. Timer.__exit__computestime.perf_counter() - self.startintoself.elapsedand returnsFalse; the falsy return tells Python not to suppress an exception from the body, andprint(timer.elapsed)reads the attribute written during exit.- Predict before running: what
timer.elapsedrepresents (elapsed seconds, a float) and what changes if__exit__returnsTruewhile the body raises.
Experiments to try
- Raise an exception inside the
withbody and confirm it propagates even though__exit__ran; then change the return toTrueand watch the exception disappear. - Remove the
return selffrom__enter__and run the same block; check whattimeris inside the block and read theAttributeErrorat the final print. - Nest two
Timercontexts and compare theirelapsedattributes; explain which__exit__runs first and why. - Rewrite
Timeras a@contextlib.contextmanagergenerator: set up beforeyield, yield the object, measure afteryield; compare the shape with the class version.
Playable lesson
Lab: Context manager lifecycle
Show __enter__, the block body, and __exit__, including the exception information passed during failure.
The lab should ask for a prediction before each state transition. Include a reset action and at least one intentionally misleading case.
Context manager lifecycle
with Timer() as timer:
# __enter__ ran, timer is the Timer instance
sum(range(100_000))
# __exit__ runs on every exit path
print(timer.elapsed)
1. __enter__
__enter__ runs first: start = perf_counter(), return self
2. body
sum(range(100_000)) completes; the result is discarded
3. __exit__
__exit__(None, None, None) runs the timing, then returns False
4. after the block
print(timer.elapsed) runs and shows the elapsed seconds
Exception info
exc_type = None
outcome: clean exit
__enter__ runs first: start = perf_counter(), return self
Predict first
The body raises and `__exit__` returns `False`. What does the caller see?
Predict first
What is passed as the three arguments to `__exit__` on a clean exit?
Predict first
What does `as timer` bind when `__enter__` returns `self`?
The trap is a habit `return True`: it swallows every exception from the body and hides real failures.
Common mistakes
- Returning
Truefrom__exit__by habit, which suppresses every exception in the body and hides failures; returnFalse(or nothing) unless suppression is the intent. - Forgetting that
__exit__must accept the three exception arguments even when the body never fails; a wrong signature raisesTypeErrorat block exit. - Placing cleanup code after the
withblock instead of inside__exit__: an exception or earlyreturnskips that code, which is exactly what the protocol exists to prevent. - Binding
aswithout returning anything from__enter__: the target becomesNoneand the first attribute access fails.
Practice: Easy
- Run the worked example, then add
printcalls inside__enter__and__exit__and record the order of events; state which lines print before and after the body. - Make the body raise
ValueError, run it, and record whether the exception reaches the caller and whattimer.elapsedholds afterwards. - Remove
return selffrom__enter__and record whattimeris inside the block.
Practice: Medium
- Change
__exit__to returnTruewith the raising body from the previous task; record what the caller sees now, then revert and explain the difference in one sentence. - Write a
Sessionmanager whose__enter__marks it open and whose__exit__marks it closed; assert the closed state after both a clean exit and an exception. - Convert
Timerto@contextlib.contextmanagerform and list what each version makes easy to inspect (the class's attributes after the block, the generator's setup-to-yield flow).
Practice: Hard
- Design a
Transactionmanager that commits on a clean__exit__and rolls back on an exception, returningFalseso the error still surfaces; test both paths and one nested pair. - Build a failure lab:
__exit__returningTrueand swallowing aValueError; an__exit__with the wrong arity and theTypeErrorat block exit; cleanup placed after the block that areturninside the block skips. Explain each mechanism and the fix. - Connect this lesson to file handling: explain what
open()provides as a context manager (which file methods run at enter and exit, when the file closes) and one consequence of leaving a file open after an exception.
Lesson checklist
- I can trace the order of
__enter__, the body, and__exit__, including a body that raises. - I can name the three arguments
__exit__receives and what each holds on a clean exit. - I can write a class-based timer that measures a block through the protocol.
- I can say what a truthy return from
__exit__does and when that is the wrong choice.
Remember
The context manager protocol brackets a block with two methods: `__enter__` prepares and returns what `as` binds, and `__exit__` always runs afterwards, receiving the exception details and deciding whether to suppress. The worked example's `Timer` measures the block and returns `False`, so failures still surface; the guarantee is that release happens on every path, including exceptions and early returns.
Interview angles
What is the main purpose of **__enter__**?+
__enter__ runs when a with block begins and returns the value bound by as, if any.
What should you pay attention to when using **__exit__**?+
__exit__ runs when a with block leaves, including through an exception. Returning a truthy value indicates that the context manager handled and suppressed the exception.
How does **Resource acquisition/release** fit into this lesson?+
A context manager acquires or prepares its resource in __enter__ and releases or finalizes it in __exit__, so both halves live in one object and release runs on every exit path. The worked example's Timer brackets a measurement this way; returning False from __exit__ lets exceptions keep travelling after cleanup.
What happens if `__exit__` returns a truthy value while the block body raises?+
The truthy return tells Python the context manager handled the exception, so the exception is suppressed and execution continues after the with block. That is right when the manager's job is to absorb the failure and wrong when it hides bugs, so return False unless suppression is the intent.