Context managers · 13 / 15 Exercise Hard

Temporary setting

Objective

Create a Python program that changes a global setting only during a with block and restores it on exit, even if there is an error. Use a context manager written with @contextmanager.

Instructions

  • Define the global dictionary config = {"decimals": 2} and the function show(x), which returns x formatted with the number of decimals given by the setting.
  • Write temporary(key, value): it stores the previous value, sets the new one, does yield and in finally restores it.
  • Read a real number x, an integer n and n integers d (decimals). For each d: inside with temporary("decimals", d), if d is greater than 6 raise ValueError with the message too many decimals; otherwise show With d: x.
Input
3.14159
3
0
8
3
Output
With 0: 3
Normal: 3.14
Error: too many decimals
Normal: 3.14
With 3: 3.142
Normal: 3.14

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

Start exercise