Fix the Bug: Missing Cleanup
Intermediate · Fix the bug · from Python Context Managers: The with Statement and Building Your Own
From the lesson: Python Context Managers: The with Statement and Building Your Own
Imagine walking through an automatic door at a grocery store. You don't have to push it open or remember to close it behind you. The door opens when you approach and closes when you walk through. It just handles itself.
Read the lessonThis context manager is supposed to always print the cleanup message, even when an error occurs inside the block. But the cleanup never runs when there's an error. Fix the @contextmanager function so cleanup always happens.
The expected output should be:
Setup done
Working...
Cleanup donefrom contextlib import contextmanager
@contextmanager
def managed_resource():
print('Setup done')
yield
print('Cleanup done')
try:
with managed_resource():
print('Working...')
raise ValueError('oops')
except ValueError:
pass
More Context Manager exercises
- Predict the Output: Basic withIntermediate
- Write a Logging Context ManagerIntermediate
- Write an Indentation Context ManagerAdvanced
- Refactor: Replace try/finally with a Context ManagerAdvanced
- Build a Batch Processor Context ManagerAdvanced
All Python exercises · 50 practice problems · Error Handling quiz