Refactor: Replace try/finally with a Context Manager
Advanced · Refactor · 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 lessonRefactor this code to use a context manager class called ConnectionSimulator instead of try/finally. The output must remain exactly the same.
Original code:
connected = False
try:
connected = True
print('Connected: True')
print('Sending data...')
finally:
connected = False
print('Connected: False')Your class should set self.connected in __enter__ and reset it in __exit__. Print the same messages.
# Refactor into a ConnectionSimulator context manager class
More Context Manager exercises
- Predict the Output: Basic withIntermediate
- Write a Logging Context ManagerIntermediate
- Fix the Bug: Missing CleanupIntermediate
- Write an Indentation Context ManagerAdvanced
- Build a Batch Processor Context ManagerAdvanced
All Python exercises · 50 practice problems · Error Handling quiz