Assertions
suggest changeAn assertion is a check that something you believe to be true really is true at a given point in the program. If the condition is false, Python raises AssertionError and the program stops right where your assumption broke, instead of continuing with bad data and failing somewhere far away later.
Assertions catch bugs in your own code. They are not a way to handle bad user input, missing files or network errors, because they can be switched off.
This article covers:
- the
assertstatement andAssertionError - assertion messages and when they are evaluated
- the parentheses pitfall
python -O,__debug__, and why assertions can disappear- side effects in assertions
- when to use
assertand when to raise an exception - invariants, unreachable code with
typing.assert_never, and type narrowing assertin pytest tests
All examples were run with Python 3.13. File paths in tracebacks are shortened.
The assert statement
The syntax is:
assert condition
assert condition, message
If condition is truthy, nothing happens. If it is falsy, Python raises AssertionError, using message (if given) as the exception argument.
def average(values):
assert len(values) > 0, "average() needs at least one value"
return sum(values) / len(values)
print(average([2, 4, 9]))
print(average([]))
5.0
Traceback (most recent call last):
File "average.py", line 6, in <module>
print(average([]))
~~~~~~~^^^^
File "average.py", line 2, in average
assert len(values) > 0, "average() needs at least one value"
^^^^^^^^^^^^^^^
AssertionError: average() needs at least one value
Without the assertion the second call would fail with ZeroDivisionError: division by zero, which says what went wrong but not why. The assertion states the assumption (the list must not be empty) and the traceback points to the exact line that checks it. Recent Python versions also underline the failing expression with ^^^^.
AssertionError is a normal exception
AssertionError is an ordinary subclass of Exception. The message is stored in args and is what str(e) returns. The message doesn't have to be a string: any object works.
try:
assert 1 + 1 == 3, "math is broken"
except AssertionError as e:
print(f"{type(e).__name__}: {e}")
print(e.args)
try:
assert None
except AssertionError as e:
print(f"no message: {e!r}, args={e.args}")
# the message can be any object, not only a string
try:
assert False, {"code": 42, "where": "startup"}
except AssertionError as e:
print(e.args[0]["code"])
print(issubclass(AssertionError, Exception))
AssertionError: math is broken
('math is broken',)
no message: AssertionError(), args=()
42
True
You can catch AssertionError, but you rarely should in application code. A failed assertion means the program is in a state you didn't expect, and carrying on is usually worse than stopping. A common exception is a top-level handler that logs every uncaught error before exiting (see Logging exceptions).
Note that except Exception: catches AssertionError too. That is one more reason to avoid catching everything.
The message is evaluated only on failure
The expression after the comma is evaluated only if the assertion fails. You can therefore put an f-string or even a function call there without paying for it when the check passes:
def expensive_report():
print(" building report...")
return "details"
x = 5
assert x > 0, expensive_report()
print("first assert passed, message was not built")
try:
assert x < 0, expensive_report()
except AssertionError as e:
print("failed with:", e)
first assert passed, message was not built
building report...
failed with: details
Put the values that matter in the message, for example f"expected 2 users, got {n}". A bare assert n == 2 failing in production tells you very little.
Pitfall: assert is a statement, not a function
assert is a keyword, like return. Writing it like a function call with parentheses around both parts creates a tuple, and a non-empty tuple is always true:
x = 0
assert (x > 0, "x must be positive")
print("this always runs")
tuple_assert.py:2: SyntaxWarning: assertion is always true, perhaps remove parentheses?
assert (x > 0, "x must be positive")
this always runs
The assertion never fails. Python warns about it at compile time, but warnings are easy to miss. Write assert x > 0, "x must be positive".
Parentheses around the condition alone are fine. To split a long assertion over several lines, wrap the condition and the message separately:
assert (
first_value <= middle_value <= last_value
), f"not ordered: {first_value}, {middle_value}, {last_value}"
Assertions can be turned off: python -O
When you run Python with the -O flag (or with the environment variable PYTHONOPTIMIZE set to a non-empty value), the compiler removes every assert statement. The built-in constant __debug__ is True normally and False under -O.
print("__debug__ =", __debug__)
assert False, "assertions are enabled"
print("reached the end")
python debug_flag.py:
__debug__ = True
Traceback (most recent call last):
File "debug_flag.py", line 2, in <module>
assert False, "assertions are enabled"
^^^^^
AssertionError: assertions are enabled
python -O debug_flag.py:
__debug__ = False
reached the end
The statement assert cond, msg behaves like this code:
if __debug__:
if not cond:
raise AssertionError(msg)
and because __debug__ is a compile-time constant, the whole block is dropped from the bytecode under -O. You can see it with dis:
import dis
src = "assert x > 0, 'x must be positive'"
for level in (0, 1):
print(f"--- optimize={level}")
dis.dis(compile(src, "<demo>", "exec", optimize=level))
--- optimize=0
0 RESUME 0
1 LOAD_NAME 0 (x)
LOAD_CONST 0 (0)
COMPARE_OP 148 (bool(>))
POP_JUMP_IF_TRUE 7 (to L1)
LOAD_ASSERTION_ERROR
LOAD_CONST 1 ('x must be positive')
CALL 0
RAISE_VARARGS 1
L1: RETURN_CONST 2 (None)
--- optimize=1
RESUME 0
RETURN_CONST 0 (None)
With optimize=1 (what -O uses) nothing is left: no comparison and no raise. So when assertions are on, a passing assert costs one comparison, and under -O it costs nothing.
Few people run Python with -O, but some deployment setups do, and you can't control how users run your library. Write code that is still correct with every assertion deleted.
Expensive checks with if __debug__
An assertion can do more work than a simple comparison. For checks that are too slow to keep in an optimized build, put them under if __debug__:. The compiler removes the whole block under -O, just like an assert:
def merge_sorted(a, b):
if __debug__:
# expensive O(n) checks, skipped entirely under -O
assert all(x <= y for x, y in zip(a, a[1:])), "a is not sorted"
assert all(x <= y for x, y in zip(b, b[1:])), "b is not sorted"
out, i, j = [], 0, 0
while i < len(a) and j < len(b):
if a[i] <= b[j]:
out.append(a[i]); i += 1
else:
out.append(b[j]); j += 1
out.extend(a[i:])
out.extend(b[j:])
return out
print(merge_sorted([1, 4, 9], [2, 3, 10]))
print(merge_sorted([5, 1], [2]))
python merge.py:
[1, 2, 3, 4, 9, 10]
Traceback (most recent call last):
File "merge.py", line 17, in <module>
print(merge_sorted([5, 1], [2]))
~~~~~~~~~~~~^^^^^^^^^^^^^
File "merge.py", line 4, in merge_sorted
assert all(x <= y for x, y in zip(a, a[1:])), "a is not sorted"
~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: a is not sorted
python -O merge.py:
[1, 2, 3, 4, 9, 10]
[2, 5, 1]
Under -O the bad input goes through unchecked and produces an unsorted result. That is acceptable here only because passing unsorted lists is a programming error in the caller.
Pitfall: side effects inside assert
Because assertions can be removed, the condition must never do work the program depends on. This code consumes an item from the queue only when assertions are enabled:
queue = ["job1", "job2"]
# BAD: the pop() happens only when assertions are enabled
assert queue.pop(0) == "job1"
print("remaining:", queue)
python prints remaining: ['job2'], while python -O prints remaining: ['job1', 'job2']. The program behaves differently depending on a command-line flag. Do the work first, then assert on the result:
queue = ["job1", "job2"]
job = queue.pop(0) # do the work unconditionally
assert job == "job1", f"unexpected job {job!r}"
print("remaining:", queue)
The same applies to the walrus operator. A name assigned inside an assertion doesn't exist when assertions are off:
import math
def hypot(a, b):
return math.sqrt(a * a + b * b)
r = hypot(3, 4)
assert math.isclose(r, 5.0), r
assert 0.1 + 0.2 != 0.3 # exact float comparison is fragile
assert math.isclose(0.1 + 0.2, 0.3) # compare with a tolerance instead
data = {"users": [{"name": "ann"}, {"name": "bob"}]}
assert (n := len(data["users"])) == 2, f"expected 2 users, got {n}"
print("all checks passed, n =", n)
python walrus.py prints all checks passed, n = 2. With python -O walrus.py:
Traceback (most recent call last):
File "walrus.py", line 13, in <module>
print("all checks passed, n =", n)
^
NameError: name 'n' is not defined
The example also shows math.isclose(). Asserting exact equality of floating-point results is a common source of false failures, so compare with a tolerance.
When to use assert and when to raise
The rule: use assert for conditions that can only be false if your code has a bug. Use raise for anything that can go wrong at run time even when the code is correct.
Things that can go wrong in correct code include invalid arguments to a public function, bad user input, a missing file, a malformed config or a network timeout. Handle those with explicit checks and a specific exception such as ValueError, TypeError or a custom exception type. See Raising Exceptions.
This function uses assert for argument validation, which is wrong:
def withdraw_bad(balance, amount):
assert amount > 0, "amount must be positive"
return balance - amount
try:
print("new balance:", withdraw_bad(100, -50))
except AssertionError as e:
print("AssertionError:", e)
python prints AssertionError: amount must be positive. python -O prints new balance: 150, so a negative withdrawal quietly adds money. The validation vanished. The correct version raises a real exception for bad input and keeps assert for an internal sanity check:
def withdraw(balance, amount):
if amount <= 0:
raise ValueError(f"amount must be positive, got {amount}")
if amount > balance:
raise ValueError(f"insufficient funds: balance={balance}, amount={amount}")
new_balance = balance - amount
assert 0 <= new_balance < balance # internal sanity check
return new_balance
try:
withdraw(100, -50)
except ValueError as e:
print("ValueError:", e)
print(withdraw(100, 30))
ValueError: amount must be positive, got -50
70
The assert here can't fail unless the arithmetic above it is wrong, which makes it a good assertion. Callers also get a ValueError they can catch and handle, instead of an AssertionError, which signals a bug.
Good places for assert:
- Invariants: facts about an object's internal state that every method must preserve.
- Postconditions: checking that a result your function computed has the expected shape.
- Preconditions of private helpers: arguments that come from your own code, not from callers you don't control.
- "Can't happen" branches: the
elseof anif/elifchain that should cover every case. - Type narrowing: telling the type checker something you know that it can't prove.
Always-on checks
If a check must stay active even under -O, don't use assert. Use an if and raise, or a small helper:
class InternalError(Exception):
"""A bug in this program, not a problem with the input."""
def check(condition: bool, message: str = "internal check failed") -> None:
# unlike assert, this runs even under python -O
if not condition:
raise InternalError(message)
def apply_discount(price_cents: int, percent: int) -> int:
result = price_cents * (100 - percent) // 100
check(0 <= result <= price_cents, f"bad discount result {result}")
return result
print(apply_discount(1999, 15))
try:
apply_discount(1999, 150)
except InternalError as e:
print("InternalError:", e)
1699
InternalError: bad discount result -1000
The output is the same with and without -O. The difference from assert is that the message argument is always evaluated, even when the check passes.
Checking invariants
A class invariant is a fact about an object's internal state that must hold after every public method. A private _check() method full of assertions, called at the end of each mutating method, catches corruption at the moment it happens:
import heapq
class TopN:
"""Keeps the n largest numbers seen so far."""
def __init__(self, n):
if n < 1:
raise ValueError("n must be >= 1")
self.n = n
self._heap = [] # min-heap of at most n items
def _check(self):
assert len(self._heap) <= self.n, f"heap too big: {len(self._heap)}"
assert all(self._heap[0] <= x for x in self._heap), "heap order broken"
def add(self, x):
if len(self._heap) < self.n:
heapq.heappush(self._heap, x)
elif x > self._heap[0]:
heapq.heapreplace(self._heap, x)
self._check()
def result(self):
return sorted(self._heap, reverse=True)
top = TopN(3)
for x in [5, 1, 9, 3, 7, 2, 8]:
top.add(x)
print(top.result())
top._heap.append(-1) # simulate a bug that corrupts internal state
top.add(4)
[9, 8, 7]
Traceback (most recent call last):
File "invariant.py", line 32, in <module>
top.add(4)
~~~~~~~^^^
File "invariant.py", line 21, in add
self._check()
~~~~~~~~~~~^^
File "invariant.py", line 13, in _check
assert len(self._heap) <= self.n, f"heap too big: {len(self._heap)}"
^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: heap too big: 4
n comes from the caller, so the constructor validates it with ValueError. The heap is private state, so assert is the right tool there.
Unreachable code with typing.assert_never
For a branch that should never run, assert False, "unreachable" works. A better tool is typing.assert_never() (Python 3.11+). At run time it raises AssertionError. Static type checkers such as mypy and pyright also report an error before you run the code if they can see that the branch is reachable, for example after you add a new enum member and forget to handle it:
from enum import Enum
from typing import assert_never
class Shape(Enum):
CIRCLE = "circle"
SQUARE = "square"
TRIANGLE = "triangle"
def corners(shape: Shape) -> int:
match shape:
case Shape.CIRCLE:
return 0
case Shape.SQUARE:
return 4
case _:
assert_never(shape)
print(corners(Shape.SQUARE))
print(corners(Shape.TRIANGLE))
4
Traceback (most recent call last):
File "never.py", line 19, in <module>
print(corners(Shape.TRIANGLE))
~~~~~~~^^^^^^^^^^^^^^^^
File "never.py", line 16, in corners
assert_never(shape)
~~~~~~~~~~~~^^^^^^^
File "...\Lib\typing.py", line 2654, in assert_never
raise AssertionError(f"Expected code to be unreachable, but got: {value}")
AssertionError: Expected code to be unreachable, but got: <Shape.TRIANGLE: 'triangle'>
A type checker flags the assert_never(shape) line because shape can still be Shape.TRIANGLE there. assert_never is an ordinary function call, not an assert statement, so -O does not remove it.
Type narrowing
Type checkers understand assert. After assert x is not None or assert isinstance(x, T), they treat x as the narrower type for the rest of the block. This removes "might be None" errors in places where you know better than the checker:
import re
APP_VERSION = "3.13.15" # a constant in our own code
def version_tuple() -> tuple[int, int, int]:
m = re.fullmatch(r"(\d+)\.(\d+)\.(\d+)", APP_VERSION)
# m is re.Match[str] | None; after the assert it is re.Match[str]
assert m is not None, f"bad APP_VERSION {APP_VERSION!r}"
major, minor, patch = (int(g) for g in m.groups())
return major, minor, patch
def describe(value: int | str) -> str:
if isinstance(value, int):
return f"number {value}"
assert isinstance(value, str) # documents (and checks) the only remaining case
return f"text {value.upper()}"
print(version_tuple())
print(describe(7), "/", describe("abc"))
(3, 13, 15)
number 7 / text ABC
Use this only for values you control. If the string came from a user or a file, a failed match is an expected situation and needs a real error (raise ValueError(...)), not an assertion.
assert in tests
pytest uses plain assert statements for test checks. Before running a test module, it rewrites the assertions in it so that a failure shows the values involved, not just AssertionError:
def restock(stock, item, qty):
new = dict(stock)
new[item] = new.get(item, 0) + qty
return new
def test_restock_adds_quantity():
stock = {"apple": 3, "pear": 1}
assert restock(stock, "apple", 2) == {"apple": 5, "pear": 1}
def test_restock_new_item():
result = restock({"apple": 3}, "kiwi", 4)
assert result == {"apple": 3, "kiwi": 5}
def test_total():
items = [3, 1, 4]
assert sum(items) > 10, "not enough stock"
python -m pytest -q test_inventory.py (pytest 9.1):
.FF [100%]
================================== FAILURES ===================================
____________________________ test_restock_new_item ____________________________
def test_restock_new_item():
result = restock({"apple": 3}, "kiwi", 4)
> assert result == {"apple": 3, "kiwi": 5}
E AssertionError: assert {'apple': 3, 'kiwi': 4} == {'apple': 3, 'kiwi': 5}
E
E Omitting 1 identical items, use -vv to show
E Differing items:
E {'kiwi': 4} != {'kiwi': 5}
E Use -v to get more diff
test_inventory.py:12: AssertionError
_________________________________ test_total __________________________________
def test_total():
items = [3, 1, 4]
> assert sum(items) > 10, "not enough stock"
E AssertionError: not enough stock
E assert 8 > 10
E + where 8 = sum([3, 1, 4])
test_inventory.py:16: AssertionError
=========================== short test summary info ===========================
FAILED test_inventory.py::test_restock_new_item - AssertionError: assert {'ap...
FAILED test_inventory.py::test_total - AssertionError: not enough stock
2 failed, 1 passed in 0.04s
pytest shows the diff of the two dicts and the intermediate value sum([3, 1, 4]), plus your custom message. pytest rewrites only test modules and conftest.py, so assertions in your application code keep the normal, shorter output. Don't run tests with -O: the test assertions would be stripped and every test would pass.
unittest uses methods like self.assertEqual() and self.assertIn() instead of assert. They also work under -O and print helpful diffs. See Choosing Assertions Within Unittests and Unit tests with pytest. To check that code raises an exception, see Asserting on Exceptions.
Summary
assert cond, msgraisesAssertionError(msg)ifcondis falsy.msgis evaluated only on failure.- Don't put parentheses around the condition and message together:
assert (cond, msg)is always true. python -O(orPYTHONOPTIMIZE) removes all assertions andif __debug__:blocks. Code must stay correct without them.- Never put side effects, including walrus assignments, inside an assertion.
- Use
assertfor internal invariants, postconditions and "can't happen" cases. Useraise ValueError/TypeError(or your own exceptions) for input validation and run-time errors. - Use
typing.assert_never()for exhaustiveness checks that a type checker can verify. assert x is not Noneandassert isinstance(x, T)narrow types for static checkers.- In pytest, plain
assertgives detailed failure reports.