Python Master Course V2 — 104. Context Managers and Deterministic Cleanup
SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 11 · LESSON 104 OF 200
Context Managers and Deterministic Cleanup
Study: 90–120 minutes · Prerequisites: Lessons 101–102, functions, classes, exceptions and tests.
Video lesson
Video not yet available. A verified video URL/player will be added when supplied.
Learning outcomes
Explain context managers and deterministic cleanup, reason about runtime behavior, apply the technique in a maintainable program, and test normal, boundary and invalid inputs.
Understand and apply: Context Managers and Deterministic Cleanup
After successful entry, the with statement calls __exit__ on normal or exceptional completion. Entry failure and abrupt process termination require separate consideration. contextlib.contextmanager builds context managers from generators.
A resource has a lifetime as well as a value
An open file, temporary directory or held lock needs an explicit owner and an exit point. A context manager describes that lifetime. The with statement obtains the manager, calls __enter__, binds the value returned by __enter__ after as, and executes the body. After a successful entry, it calls __exit__ when the body finishes normally or leaves through an exception. The returned value can be the resource itself rather than the manager.
For a normal exit, __exit__ receives three None values. For an exceptional exit, it receives the exception type, instance and traceback. Returning False or None allows the exception to propagate. Returning a truthy value suppresses it, which should be reserved for a specifically documented recovery policy. Cleanup and successful completion are separate facts: closing a file does not mean its processing succeeded.
Python example
from io import StringIO
class ManagedBuffer:
def __enter__(self):
self.buffer = StringIO()
return self.buffer
def __exit__(self, exc_type, exc_value, traceback):
self.buffer.close()
print("closed:", self.buffer.closed)
return False
try:
with ManagedBuffer() as output:
output.write("partial result")
raise ValueError("processing failed")
except ValueError:
print("failure propagated")
Expected output
closed: True
failure propagated
The caller sees the ValueError after the buffer closes. If __enter__ fails, Python does not call that manager’s __exit__; acquisition must undo any partial work before reraising. Likewise, context managers cannot guarantee cleanup after abrupt process termination. Avoid calling the protocol methods manually, since doing so makes it easy to miss the exception path or call cleanup twice.
Use one yield to express acquisition and release
contextlib.contextmanager adapts a generator with exactly one yield. Code before yield performs setup, the yielded object becomes the as value, and code after yield handles exit. Put release operations in finally. If the body raises, the exception is injected back at the yield point; catching it without reraising means it has been handled and will suppress it.
Python example
from contextlib import contextmanager
@contextmanager
def marked_session():
print("acquire")
try:
yield "ready"
finally:
print("release")
with marked_session() as status:
print(status)
Expected output
acquire
ready
release
Verify a real temporary workspace is removed
TemporaryDirectory is already a standard context manager, so prefer it to writing a custom deletion routine. The test creates only a uniquely allocated temporary workspace, writes inside it, and deliberately fails. The path object can still exist as a Python value afterward even though the filesystem object has been removed.
Python example
from pathlib import Path
from tempfile import TemporaryDirectory
try:
with TemporaryDirectory() as directory:
workspace = Path(directory)
report = workspace / "report.txt"
report.write_text("draft", encoding="utf-8")
print("exists inside:", report.exists())
raise RuntimeError("simulated failure")
except RuntimeError:
print("caught failure")
print("exists afterward:", workspace.exists())
Expected output
exists inside: True
caught failure
exists afterward: False
Nested managers exit in reverse entry order, which is useful when a file must close before its parent workspace is removed. For a dynamic number of resources, ExitStack can register managers and unwind those already entered if a later acquisition fails. Keep all reads from a lazy file iterator inside the file’s owning with block; returning that iterator after leaving the block gives the consumer a closed file.
Use the same lifetime reasoning for the project tests: prove normal cleanup, exceptional cleanup, propagation of the original processing error and the absence of temporary files afterward. Also test acquisition failure separately. A context manager establishes a cleanup boundary; resource-specific behavior, such as commit versus rollback, still needs its own contract.
Progressive runnable examples
Requires Python 3.10+. Save as lesson104.py and run python lesson104.py or python3 lesson104.py. Expected outputs below are illustrative and not claimed to have been executed on Smartyfy.
Example 1 — Core mechanism
from contextlib import contextmanager
@contextmanager
def session():
print('open')
try:
yield 'ready'
finally:
print('close')
with session() as status:
print(status)
Expected output:
open
ready
close
Guided practical project
Project: Create a safe temporary-file workflow using tempfile.TemporaryDirectory and test cleanup after exceptions.
Use the complete implementation and explicit contract in the worked explanation above. Reproduce its deterministic sample, test the stated boundary and failure cases, and explain the documented limitations before adapting it.
Common mistakes and debugging
- Adding abstraction without a demonstrated need.
- Hiding state or unexpected side effects.
- Assuming type hints replace validation.
- Ignoring resource cleanup or error propagation.
- Measuring performance on unrepresentative data.
- Failing to test boundary and error cases.
Debug by reproducing the smallest failing input, inspecting the traceback and intermediate values, then adding a regression test.
Practice with explained answers
Predict each result before opening the answer. Trace state changes and explain the contract as well as the output.
Is the name after as always the context-manager object?
No. It is whatever __enter__ returns. ManagedBuffer returns its StringIO buffer, so output refers to that buffer while the with machinery retains the manager for cleanup.
What changes if ManagedBuffer.__exit__ returns True?
The ValueError from the body is suppressed after the buffer closes. The except ValueError branch does not run. This could make a failed report appear successful, so return False unless suppression is an intentional, narrow part of the contract.
Does __exit__ run when __enter__ raises?
No. Entry never completed, so that manager must clean up any resources it partially acquired. Previously entered outer managers still unwind as the exception leaves their bodies.
Why must a contextmanager generator yield exactly once?
The yield separates setup from the one with-body execution and provides its as value. No yield fails to enter; a second yield fails to complete the context-manager protocol. Reuse the factory to create a fresh manager for another with block.
What does the temporary-workspace example prove?
The file exists while the workspace is owned, the body’s RuntimeError reaches the handler, and the directory is gone afterward. It tests real cleanup following a controlled processing failure without deleting any preexisting user directory.
Why is returning a lazy file iterator from inside with open(…) unsafe?
The with block closes the file before the caller advances the returned iterator. Consume inside the resource scope, return already-computed results, or return a context manager that transfers an explicit scoped lifetime to the caller.
Mastery checkpoint
Explain the concept without notes, reproduce the core example, finish the project, run three tests and justify when the technique is appropriate. No account-synced completion or certification is claimed.
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.