AssertionError

AssertionError is a built-in exception that occurs when an assert statement fails.

The assert statement lets you test if a condition in your code returns True. If the condition evaluates to False, then Python raises an AssertionError.

This can help you verify that your code behaves as expected, which is a useful debugging aid. However, remember that Python won’t raise AssertionError exceptions if you run Python with the -O optimization flag. Therefore, you shouldn’t use it in production code.

AssertionError Practical Use Cases

It’s uncommon and not recommended to raise or catch an AssertionError manually. Only the assert statement is meant to raise this exception.

AssertionError Example

An example of when the exception appears:

Python
>>> x = 10
>>> assert x == 5, "x is not equal to 5"
Traceback (most recent call last):
  ...
AssertionError: x is not equal to 5

Tutorial

Python's assert: Debug and Test Your Code Like a Pro

In this tutorial, you'll learn how to use Python's assert statement to document, debug, and test code in development. You'll learn how assertions might be disabled in production code, so you shouldn't use them to validate data. You'll also learn about a few common pitfalls of assertions in Python.

intermediate best-practices python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated March 6, 2025 • Reviewed by Martin Breuss