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 functionshow(x), which returnsxformatted with the number of decimals given by the setting. - Write
temporary(key, value): it stores the previous value, sets the new one, doesyieldand infinallyrestores it. - Read a real number
x, an integernandnintegersd(decimals). For eachd: insidewith temporary("decimals", d), ifdis greater than 6 raiseValueErrorwith the messagetoo many decimals; otherwise showWith d: x.
3.14159
3
0
8
3
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