Context managers · 12 / 15 Exercise Hard

Transaction with rollback

Objective

Create a Python program that simulates a bank transaction: if something goes wrong inside the block, the balance goes back to its previous value. For that, __exit__ can decide what to do with the error.

Instructions

  • Create the class Account (with a balance attribute) and the class Transaction, a context manager that on entering stores a copy of the balance and returns the account.
  • In __exit__, if there was an error (the first parameter is not None) restore the balance, show Rolled back: message and return True to suppress the error. If there was no error, return False.
  • Read the initial balance, an integer n and n operations with the format + amount or - amount (for example - 200). Each one runs inside a transaction.
  • If subtracting leaves the balance negative, raise ValueError with the message insufficient balance (after subtracting). After each operation show Balance: s.
Input
100
3
+ 50
- 200
- 30
Output
Balance: 150
Rolled back: insufficient balance
Balance: 150
Balance: 120

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

Start exercise