Context managers · 7 / 15 Exercise Medium

Nested levels

Objective

Create a Python program that nests several with blocks one inside another and shows each opening and closing with an indentation that depends on the nesting level.

Instructions

  • Create the class Level, a context manager with a class attribute depth that starts at 0 and counts how many blocks are open.
  • On entering, show Opens name with 2 spaces of indentation for each level already open, and increase the depth. On leaving, decrease the depth and show Closes name with the indentation of the current level.
  • Read an integer n and then n names. Create a recursive function that opens one with per name, one inside another, and in the deepest one shows Depth: k with the corresponding indentation.
Input
3
a
b
c
Output
Opens a
  Opens b
    Opens c
      Depth: 3
    Closes c
  Closes b
Closes a

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise