AssertionError
Error message
AssertionError
Quick summary
An assert statement checked a condition that evaluated to false, indicating a programming bug.
Why this happens
An invariant or precondition was violated
A function received unexpected input (programming error, not user error)
An internal state assumption was wrong
Minimal example
def get_first(items):
assert len(items) > 0 # AssertionError if empty
return items[0]
get_first([]) # AssertionErrordef get_first(items):
if not items:
raise ValueError("List cannot be empty")
return items[0]
# get_first([]) raises ValueError with a clear messageReplace assert with explicit if/raise for validation that must run in production. Assertions can be disabled with -O flag.
How to diagnose
Read the assert statement and its message
Check the values being asserted
Determine if the assertion is correct or the code has a bug
How to fix
Fix the code that caused the assertion to fail
Add a more descriptive message to the assert statement
Replace assert with explicit if/raise for production validation
How to prevent
Use assertions for internal invariants, not user input validation
Write clear assertion messages
Don't rely on assertions for production error handling (they can be disabled)
Related Resources
Related Lessons
- Unit Testing
Assertions.