Editor

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 lesson

Refactor 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

All Python exercises · 50 practice problems · Error Handling quiz