AssertionError
assert cond, msg is shorthand for "if not cond: raise AssertionError(msg)" — but only while __debug__ is true, so it must never guard real input.
Demo
def set_age(age): assert 0 <= age <= 150, f'age out of range: {age}' return age set_age(42)
The message after the comma becomes str(e), which is what the traceback line shows. Everything here depends on asserts being enabled: run the same file with python -O and set_age(-5) returns -5 without complaint. That is why this pattern belongs in tests and internal sanity checks, while user-supplied ages need an if + raise ValueError.
Constructor
| Name | Type | Required | Description |
|---|---|---|---|
| *args | object | no | assert passes its message expression as the single argument; with no message there are no args and the traceback line is bare AssertionError. |
Attributes
| Attribute | Type | Meaning |
|---|---|---|
| args | tuple | The assert message as a one-element tuple, or () when the assert had no message. |
Common patterns
def pop_min(heap): assert heap, 'pop_min() on empty heap — caller should check' return heap.pop(0)
def set_age(age): if not 0 <= age <= 150: raise ValueError(f'age out of range: {age}') return age
def test_total(): assert total([1, 2]) == 3
Examples
Pitfalls
x = -1 assert (x > 0, 'x must be positive') 'passed'
x = -1 assert x > 0, 'x must be positive' 'passed'
src = '\n'.join([ 'def withdraw(balance, amount):', " assert amount > 0, 'amount must be positive'", ' return balance - amount', ]) ns = {} exec(compile(src, '<bank>', 'exec', optimize=1), ns) # what python -O does ns['withdraw'](100, -50)
src = '\n'.join([ 'def withdraw(balance, amount):', ' if amount <= 0:', " raise ValueError('amount must be positive')", ' return balance - amount', ]) ns = {} exec(compile(src, '<bank>', 'exec', optimize=1), ns) # what python -O does ns['withdraw'](100, -50)
src = 'items = [3, 1]\nassert items.pop() == 1' ns = {} exec(compile(src, '<s>', 'exec', optimize=1), ns) # what python -O does ns['items']
src = 'items = [3, 1]\nlast = items.pop()\nassert last == 1' ns = {} exec(compile(src, '<s>', 'exec', optimize=1), ns) # what python -O does ns['items']
When to use
- Internal invariants: "this can only happen if my code has a bug"
- Test code (pytest, unittest) and debugging checks during development
- Documenting an assumption right where it is relied on
- Validating arguments, user input, config or file contents → ValueError / TypeError
- Security or permission checks — they vanish under -O
- Expressions with side effects
Notes
FAQ
Put it after a comma: assert x > 0, f'x must be positive, got {x}'. The message expression is only evaluated when the assertion fails and becomes the exception's argument, so the traceback ends with AssertionError: x must be positive, got -1. Do not wrap condition and message in parentheses — that creates a tuple, which is always true.