Assert Statements Are Removed When Python Runs With -O

assert is for checking your own assumptions while developing, not for guarding production code: Python strips every assert statement when it runs with optimizations on, so the check silently disappears.

Optimizations are on when Python runs:

  • with the -O or -OO command-line option, or
  • with the PYTHONOPTIMIZE environment variable set to a non-empty value.
def withdraw(account, amount):
    assert amount > 0  # gone under -O
    if amount > account.balance:
        raise ValueError("insufficient funds")  # always runs
    account.balance -= amount
  • Use assert for internal invariants that would mean a bug in your own code if they failed.
  • Use an explicit if ...: raise ... for anything that validates input or protects data: it runs in every mode.