3 ms·
"Maybe a good analogy would be “a runtime assert”." The first example if found when googling "python invariants" was a BankAccount class that did exactly this
by UltraSane 2y ago
"Maybe a good analogy would be “a runtime assert”."
The first example if found when googling "python invariants" was a BankAccount class that did exactly this
class BankAccount:
"""
A bank account class with a representation invariant: balance is always non-negative.
"""
def __init__(self, initial_balance):
self.balance = initial_balance
assert self.balance >= 0, "Balance cannot be negative"
def deposit(self, amount):
assert amount > 0, "Deposit amount must be positive"
self.balance += amount
def withdraw(self, amount):
assert amount > 0, "Withdrawal amount must be positive"
assert self.balance >= amount, "Insufficient funds"
self.balance -= amount