assert
A one-line sanity check for things that must be true if your code is correct. It is a statement, not a function — parentheses around both parts turn it into a check that can never fail.
assert condition
assert condition, 'message'
if __debug__: if not condition: raise AssertionError(msg)
Demo
def take(stock, n): assert n <= stock, f'cannot take {n}, only {stock} left' return stock - n take(5, 3)
In the tuple trap tab, the first assert passes for every x: (x > 0, "...") is a two-item tuple, and non-empty tuples are truthy. CPython notices at compile time and prints "SyntaxWarning: assertion is always true, perhaps remove parentheses?" to stderr — easy to miss in a log, invisible here. The second form is the real check. The failed-assert message is exactly the value after the comma.
Syntax slots
| Name | Type | Required | Description |
|---|---|---|---|
| condition | expression | yes | Tested for truthiness. Falsy → AssertionError. |
| message | expression | no | Evaluated only when the assert fails, and passed to AssertionError. Any object; usually an f-string with the offending values. |
Common patterns
assert len(result) == len(items), 'lost items while merging'
def test_total(): assert total([1, 2]) == 3
assert user is not None print(user.name)
assert ( start <= end ), f'bad range {start}..{end}'
Examples
Pitfalls
x = -1 assert (x > 0, 'x must be positive') 'passed'
x = -1 assert x > 0, 'x must be positive' 'passed'
src = ''' def withdraw(balance, amount): assert amount <= balance, 'insufficient funds' return balance - amount print(withdraw(10, 50)) ''' exec(compile(src, '<demo>', 'exec', optimize=1))
src = ''' def withdraw(balance, amount): if amount > balance: raise ValueError('insufficient funds') return balance - amount print(withdraw(10, 50)) ''' exec(compile(src, '<demo>', 'exec', optimize=1))
When to use
- Invariants: things that are true unless your own code has a bug
- Tests (pytest is built on plain assert)
- Documenting an assumption at the top of a tricky block
- Validating user input, file contents or API arguments → if … raise ValueError / TypeError
- Anything with side effects in the condition — it disappears under -O
- Security or permission checks → an explicit if + raise
Notes
FAQ
assert (x > 0, "msg") asserts a two-item tuple, and non-empty tuples are always truthy. Write assert x > 0, "msg" — the comma belongs to the assert statement. CPython warns: "SyntaxWarning: assertion is always true, perhaps remove parentheses?".