Editor

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 lesson

Create a context manager called indent_block using @contextmanager from contextlib. It should take a level parameter (an integer).

  • Before the block, print 'Entering level <level>'
  • Yield the string ' ' * level (two spaces repeated level times)
  • After the block, print 'Exiting level <level>'
  • Use 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

    All Python exercises · 50 practice problems · Error Handling quiz