Simulate a banking system with double-entry bookkeeping. Every transfer creates two…
- User
Simulate a banking system with double-entry bookkeeping. Every transfer creates two ledger entries: debit from Account A and credit to Account B. Use a context manager ensuring atomicity so if credit fails, debit is rolled back.
- Assistant
Implementing atomic double-entry banking simulation
Produced Python code defining Account, LedgerEntry, Bank, and a Transaction context manager that ensures atomicity of transfers by snapshotting balances and buffering ledger entries, rolling back on simulated credit failure; includes demonstration of successful and failed transfers showing correct rollback behavior. Here's a simple Python simulation of a bank with double‑entry bookkeeping. It uses a transaction context manager to ensure debits and credits happen atomically: if anything in the transfer fails, all changes are rolled back.
from dataclasses import dataclass, field from typing import Dict, List, Optional @dataclass class Account: id: str name: str balance: float = 0.0 def __repr__(self): return f"<Account {self.id} ({self.name}) balance={self.balance:.2f}>" @dataclass class LedgerEntry: txn_id: int kind: str # 'debit' or 'credit' account_id: str amount: float def __repr__(self): return f"[txn={self.txn_id} {self.kind} {self.account_id} {self.amount:.2f}]" class Transaction: """ Context manager that snapshots account balances and pending ledger entries. On exception, restore balances and discard pending entries. """ def __init__(self, bank: "Bank"): self.bank = bank self._balance_snapshot: Dict[str, float] = {} self._ledger_len: int = 0 self._pending_entries: List[LedgerEntry] = [] def __enter__(self): # Snapshot balances and current ledger size self._balance_snapshot = {acc_id: acct.balance for acc_id, acct in self.bank.accounts.items()} self._ledger_len = len(self.bank.ledger) # Register self so Bank knows to buffer entries self.bank._current_txn = self return self def __exit__(self, exc_type, exc_val, exc_tb): # Unregister self.bank._current_txn = None if exc_type: # Roll back balances for acc_id, balance in self._balance_snapshot.items(): self.bank.accounts[acc_id].balance = balance # Discard any ledger entries that were added in this transaction self.bank.ledger = self.bank.ledger[:self._ledger_len] print(f"Transaction rolled back due to: {exc_val}") # suppress exception so program can continue return True else: # Commit buffered entries self.bank.ledger.extend(self._pending_entries) return False # don't suppress any exceptions class Bank: def __init__(self): self.accounts: Dict[str, Account] = {} self.ledger: List[LedgerEntry] = [] self._current_txn: Optional[Transaction] = None def add_account(self, id: str, name: str, balance: float = 0.0): self.accounts[id] = Account(id, name, balance) def _add_entry(self, entry: LedgerEntry): if self._current_txn is not None: self._current_txn._pending_entries.append(entry) else: self.ledger.append(entry) def debit(self, account_id: str, amount: float, txn_id: int): acct = self.accounts[account_id] if acct.balance < amount: raise ValueError(f"Insufficient funds in account {account_id}") acct.balance -= amount self._add_entry(LedgerEntry(txn_id, 'debit', account_id, amount)) def credit(self, account_id: str, amount: float, txn_id: int): acct = self.accounts[account_id] # Here you could check for errors (closed account, etc.) acct.balance += amount self._add_entry(LedgerEntry(txn_id, 'credit', account_id, amount)) def transfer(self, from_id: str, to_id: str, amount: float, simulate_failure: bool = False): # Use a monotonically increasing transaction id for simplicity txn_id = len(self.ledger) + 1 with Transaction(self): self.debit(from_id, amount, txn_id) # simulate a failure before crediting if simulate_failure: raise RuntimeError("Credit failed (simulated)") self.credit(to_id, amount, txn_id) # Demonstration bank = Bank() bank.add_account("A", "Alice", balance=100.0) bank.add_account("B", "Bob", balance=50.0) print("Before transfer:", bank.accounts) # Successful transfer bank.transfer("A", "B", 25.0) print("\nAfter successful transfer:") print("Accounts:", bank.accounts) print("Ledger:", bank.ledger) # Failing transfer: debit will be rolled back because credit fails bank.transfer("A", "B", 30.0, simulate_failure=True) print("\nAfter failed transfer (should be rolled back):") print("Accounts:", bank.accounts) print("Ledger:", bank.ledger)Running this produces output like:
Before transfer: {'A': <Account A (Alice) balance=100.00>, 'B': <Account B (Bob) balance=50.00>} After successful transfer: Accounts: {'A': <Account A (Alice) balance=75.00>, 'B': <Account B (Bob) balance=75.00>} Ledger: [[txn=1 debit A 25.00], [txn=1 credit B 25.00]] Transaction rolled back due to: Credit failed (simulated) After failed transfer (should be rolled back): Accounts: {'A': <Account A (Alice) balance=75.00>, 'B': <Account B (Bob) balance=75.00>} Ledger: [[txn=1 debit A 25.00], [txn=1 credit B 25.00]]The failed transfer raised an exception during the credit step; the context manager caught it, restored the original balances, and discarded the pending ledger entries, preserving atomicity.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.