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:
>>> x = 10
>>> assert x == 5, "x is not equal to 5"
Traceback (most recent call last):
...
AssertionError: x is not equal to 5
Related Resources
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.
For additional information on related topics, take a look at the following resources:
- Effective Python Testing With pytest (Tutorial)
- Python's Built-in Exceptions: A Walkthrough With Examples (Tutorial)
- Using Python's assert to Debug and Test Your Code (Course)
- Testing Your Code With pytest (Course)
- Effective Testing with Pytest (Quiz)
- Python's Built-in Exceptions: A Walkthrough With Examples (Quiz)