Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Exceptions

Python AssertionError

Reference for Python AssertionError: how a failed assert statement raises it, custom messages, the python -O switch, and when not to use assert.

AssertionError is raised when an assert statement finds its condition false. An assertion states something that must be true if your program is correct; if it is not, you have found a bug, and the program stops at that spot with a traceback.

assert condition, message is roughly shorthand for if __debug__ and not condition: raise AssertionError(message). The message is optional but makes the failure much easier to understand. You can also raise AssertionError by hand, and testing frameworks use it for failed checks.

Python
assert 2 + 2 == 5, "arithmetic is broken"   # AssertionError: arithmetic is broken

Try it

Python Failing and passing assertions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Assertions versus real validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
assert condition
assert condition, message
Part Description
condition Any expression. If its truth value is false, AssertionError is raised.
message Optional expression, evaluated only on failure, and passed to AssertionError.

Raises when: the condition is false and assertions are enabled (the default).

Usage notes

  • Assertions can be switched off. Running python -O (or -OO, or setting PYTHONOPTIMIZE) removes assert statements entirely and sets __debug__ to False. Never rely on an assertion for something that must always happen.
  • Not for input validation. Check arguments, user input and external data with if and raise ValueError or TypeError. Use assertions only for internal sanity checks, invariants and "this can't happen" branches.
  • No side effects in the condition. assert queue.pop() == 3 would remove an item only when assertions are on.
  • Don't wrap the condition in parentheses with a message. assert (x > 0, "message") is a non-empty tuple, which is always true, so it never fails. Recent Python versions warn about it with a SyntaxWarning.
  • Write messages that name the values, using an f-string; they are built only when the check fails, so they cost nothing on success.
  • Catching it is unusual. If you must report a failure, catch AssertionError at the top of a test or tool; otherwise let it end the program with its traceback.
  • Testing. unittest provides methods such as assertEqual() that give richer messages; pytest rewrites plain assert statements to show the compared values. Both signal failure with AssertionError.
  • Use raise AssertionError(...) or typing.assert_never() for a branch that should be unreachable, since a plain assert False is removed under -O.