Write an Indentation Context Manager
Advanced · Write the code · 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 lessonCreate a context manager called indent_block using @contextmanager from contextlib. It should take a level parameter (an integer).
'Entering level <level>'' ' * level (two spaces repeated level times)'Exiting level <level>'try/finally for safety.Then demonstrate with:
with indent_block(1) as pad:
print(f'{pad}Hello')
with indent_block(2) as pad2:
print(f'{pad2}World')from contextlib import contextmanager
# Write your indent_block context manager here
More Context Manager exercises
- Predict the Output: Basic withIntermediate
- Write a Logging Context ManagerIntermediate
- Fix the Bug: Missing CleanupIntermediate
- Refactor: Replace try/finally with a Context ManagerAdvanced
- Build a Batch Processor Context ManagerAdvanced
All Python exercises · 50 practice problems · Error Handling quiz