Predict the Output: Basic with
Intermediate · Predict the output · 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 lessonWhat will this code print? Think carefully about the order of __enter__, the block body, and __exit__.
class Door:
def __enter__(self):
print('Door opens')
return 'welcome'
def __exit__(self, exc_type, exc_val, exc_tb):
print('Door closes')
return False
with Door() as msg:
print(msg)# Type the exact output, one line per print statement
More Context Manager exercises
- Write a Logging Context ManagerIntermediate
- Fix the Bug: Missing CleanupIntermediate
- 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