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
-Oor-OOcommand-line option, or - with the
PYTHONOPTIMIZEenvironment 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
assertfor 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.