Assertions and Exceptions are not the same
What’s wrong with the withdraw_money function in the code below?
# bank.py
from dataclasses import dataclass
@dataclass
class Client:
balance: float
def withdraw_money(client: Client, amount: float):
assert client.balance >= amount, f'Insufficient funds: {client.balance}'
# Withdraw amount from the client's bank account.
client.balance -= amount
return client.balance
client = Client(balance=10.0)
new_balance = withdraw_money(client=client, amount=20.0)
print(f'The new balance is {new_balance}')
If you run it with python bank.py you’re given an error message:
$ python bank.py
Traceback (most recent call last):
File "bank.py", line 20, in <module>
new_balance = withdraw_money(client=client, amount=20.0)
File "bank.py", line 14, in withdraw_money
assert client.balance >= amount, f'Insufficient funds: {client.balance}'
AssertionError: Insufficient funds: 10.0
Which, at first sight, is correct: I am withdrawing 20.0 from a client account with a balance of 10.0, and the code is specifically written to exit if the withdrawal would put the client account into the red. So what’s the problem, then?
Read More ->
from Planet Python
via read more
No comments:
Post a Comment