Context managers · 6 / 15 Exercise Easy

Section with entry and exit

Objective

Create a Python program with a class that is a context manager: an object that can be used with with thanks to the __enter__ and __exit__ methods.

Instructions

  • Create the class Section with a constructor that receives and stores a name.
  • __enter__ must show Entering: name and return the object itself. __exit__ must show Leaving: name and return False.
  • Read an integer n and then n names. For each name use a with block with the class and, inside it, show Length: k with the length of the name.
Input
2
ana
luis
Output
Entering: ana
Length: 3
Leaving: ana
Entering: luis
Length: 4
Leaving: luis

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

Start exercise