Context managers · 11 / 15 Exercise Medium

Guaranteed cleanup

Objective

Create a Python program that shows that a context manager is always closed, even when an error occurs inside the block, and that several resources are closed in the reverse order of opening.

Instructions

  • Create the class Resource with __enter__ (which shows Open name and returns the object) and __exit__ (which shows Close name and returns False, without hiding the error).
  • Read two names and a third line that is 1 if the program must fail or 0 if not.
  • With a single with open the two resources (with Resource(a) as r1, Resource(b) as r2). Inside, show Using a and b; if it must fail, raise RuntimeError with the message processing failed; otherwise show Process finished.
  • Catch the error outside the with block and show Error: message.
Input
bd
red
1
Output
Open bd
Open red
Using bd and red
Close red
Close bd
Error: processing failed

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

Start exercise