Context managers · 14 / 15 Exercise Hard

Resource stack

Objective

Create a Python program that opens a variable number of resources and closes them all at the end in reverse order. When you do not know in advance how many with you need, ExitStack from the contextlib module is used.

Instructions

  • Define resource(name) with @contextmanager: it shows Open name, does yield of the name and in finally shows Close name.
  • Read an integer n and then n names. Inside with ExitStack() as stack go through the names: if they start with _ show Skipped: name and do not open it; otherwise open it with stack.enter_context(resource(name)) and keep it in a list.
  • Still inside the block, show Opened: k and, if there are any, Using: a, b with the names separated by comma and space.
  • When you leave the block they will close by themselves in reverse order. Then show Everything closed.
Input
3
x
_y
z
Output
Open x
Skipped: _y
Open z
Opened: 2
Using: x, z
Close z
Close x
Everything closed

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

Start exercise