What is ‘assert’ in Python?

Python Tutorials

assert is a statement in Python that is used to check whether a condition evaluates to True or not. If not, it raises the AssertionError exception.

assert [condition]

For example, assert does nothing when the condition evaluates to True, while it raises an exception when the condition evaluates to False.

>>> assert True
>>> assert False
Traceback (most recent call last):

With the assert statement, you can also print an optional message for the condition that results in False.

>>> assert 1 == '1', 'Integers and numbers are different'
Traceback (most recent call last):
AssertionError: Integers and numbers are different

When to use assert in Python?

The assert is useful in the following cases:

  1. To debug your code or detect errors early in your program. For example, a type error if not caught early, can go through several layers of code before actually raising an Exception.
  2. In documenting code for other programmers. For example, the programmer who sees assert in the code can be sure that the condition will hold from now.

The assert [condition] in Python is roughly equivalent to:

if not [condition]:
    raise AssertionError()

Leave a Reply

Your email address will not be published. Required fields are marked *