Context managers pair setup with cleanup across normal and exceptional execution. Their exception-handling behavior should be deliberate.
Before you start
You should know Python functions, collections and exceptions. Use a small isolated script or interactive session to trace the example. Pay attention to when objects are created and when work executes; iteration, binding and mutation can happen at different points in a program.
The practical goal is to reason through this situation: A with block closes a file even when parsing fails. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.
Step-by-step walkthrough
Step 1: Define resource ownership
The block owns the acquired resource for its bounded operation.
Step 2: Guarantee cleanup
With invokes the resource’s exit behavior after normal or exceptional execution.
Step 3: Suppress errors deliberately
A custom exit method returning true hides the exception, which needs an explicit recovery justification.
Worked scenario
A with block closes a file even when parsing fails.
with open('input.txt', encoding='utf-8') as source:
first_line = source.readline()The file closes after the block even if reading or processing fails. A custom context manager should release its resources while allowing unhandled failures to reach the boundary that can choose recovery.
Common mistake
Returning true from exit suppresses the exception, which may conceal a failure.
Verify the behavior
Raise inside the block and confirm cleanup; test custom suppression separately from normal release.
Interview exercise
Manage a temporary resource.
Answer and reasoning
Release it in finally or a context manager, and suppress only explicitly handled exceptions.
Continue learning
Compare the scenario with the Python interview questions and test your understanding with the Python MCQs. For terminology and implementation details, consult the reference material.