Inspired Python
def withdraw_money(customer, amount):
    assert customer['balance'] >= amount, \
        f'Balance too low; cannot withdraw {amount}'
    customer['balance'] -= amount
    return customer['balance']

>>> withdraw_money({"balance": 100.0}, amount=150)
AssertionError: Balance too low; cannot withdraw 150
# And again, this time by running `python -O` to enable optimizations
>>> withdraw_money({"balance": 100.0}, amount=150)

Python Anti-Patterns: Confusing Assertions with Exceptions

The assert statement is there to check for system invariants and not for validating your business logic. Assertion checks are disabled if you enable the optimizer in Python — so watch out!

Be Inspired Get Python tips sent to your inbox

We'll tell you about the latest courses and articles.

Absolutely no spam. We promise!