Assertions

Indices and tables

The assert Statement

assert is a built in python statement that has a variety of potential use cases. At the most basic level, it can be used to check assumptions during program execution. It can also be used to test program operation by comparing an expected outcome to the actual outcome.

The assert statement has the following form:

assert <condition>,<error message>

If the assertion condition is true, the program will continue to run. If the assertion condition is false, python will halt the program and raise an AssertionError. An optional error message can be provided to provide additional information. By default, the AssertionError provides very little information to aid in debugging the issue.

>>> assert 1 == 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError

Adding an error message can make diagnosing assertions raised much easier:

>>> assert 1 == 2, "one does not equal two"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: one does not equal two