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 showsOpen name, doesyieldof the name and infinallyshowsClose name. - Read an integer
nand thennnames. Insidewith ExitStack() as stackgo through the names: if they start with_showSkipped: nameand do not open it; otherwise open it withstack.enter_context(resource(name))and keep it in a list. - Still inside the block, show
Opened: kand, if there are any,Using: a, bwith the names separated by comma and space. - When you leave the block they will close by themselves in reverse order. Then show
Everything closed.
3
x
_y
z
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