How do assertions and the assert statement work in Python?
· Category: Python Programming
Short answer
The assert statement checks a condition and raises AssertionError if it is false. It is intended for debugging and verifying internal correctness, not for handling runtime errors caused by user input.
Steps
- Write
assert conditionorassert condition, "message". - Run with optimizations (
python -O) to disable assertions.
def calculate_discount(price, discount):
assert price >= 0, "Price must be non-negative"
assert 0 <= discount <= 1, "Discount must be between 0 and 1"
return price * (1 - discount)
print(calculate_discount(100, 0.2))
# calculate_discount(-10, 0.2) # AssertionError
Tips
- Use assertions to document invariants and catch programmer mistakes during development.
- Never use assertions to validate user input or external data; use proper error handling instead.
- Assertions can be stripped when Python runs with the
-Oor-OOflags, so do not rely on them for side effects.
Common issues
- Relying on
assertfor security checks is dangerous because optimizations remove them. - Writing
assert condition, "message"without parentheses can lead to unexpected tuple behavior in older syntax contexts. - Catching
AssertionErrorin production code is discouraged; it should indicate a bug, not an expected condition.