Python Assert Statement

In Python, the assert statement is used to check that a value returns true. It is often used to debug comparisons or values that should always be true, throwing an error with the option to add a custom message if false is returned.

 

In this tutorial, we will learn how to use the assert statement in Python with examples.

 

 

Assert Syntax

The assert statement begins with the keyword assert followed by the value/expression to check. A custom error message can be supplied as the second argument.

 

asset expression, 'message'

 

Basic Usage

Let's create a string and check if is equal to another string using assert. If true, assert will do nothing and the program will continue to run, otherwise, an AssertError exception will be returned.

 

string = 'foo'

assert string == 'foo'
assert string == 'bar'
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-5-3063568106bb> in <module>
      2 
      3 assert string == 'foo'
----> 4 assert string == 'bar'

AssertionError:

 

bar is not equal to foo, so we got an AssertionError exception.

 

Let's try another example, this time asserting if a list is empty.

 

fruit = ['strawberry', 'apple', 'orange']

assert len(fruit) != 0

print('No errors!')
No errors!

 

assert did nothing as the list is not empty and the comparison statement to evaluate this returned True.

 

Custom Assertion Message

The error returned from assert can be more useful with a custom error message describing what happened. We can do this passing a , (comma) after the expression followed by a string containing the message.

 

string = 'foo'

assert string == 'foo', 'string does not match'
assert string == 'bar', 'string does not match'
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-6-9d2938b8e68b> in <module>
      2 
      3 assert string == 'foo', 'string does not match'
----> 4 assert string == 'bar', 'string does not match'

AssertionError: string does not match

 

 

Handling assert Errors

The easiest way to handle Python assert errors is to put the assert(s) inside a try except block. In the example below, we will catch the AssertionError exception and print what the error is.

 

fruit = []

try:
    assert len(fruit) != 0, 'list fruit is empty'
    
    print('Do something if no errors')
    
except AssertionError as e:
    
    print('AssertionError:', e)
AssertionError: list fruit is empty

 

It is possible to add an else statement after a try except block. This will allow you to place only assertions in the try statement and run code in the else statement if no errors occurred.

 

fruit = ['strawberry', 'apple', 'orange']

try:
    assert len(fruit) != 0, 'list fruit is empty'
    
except AssertionError as e:
    print('AssertionError:', e)
    
else:    
    print(fruit)
['strawberry', 'apple', 'orange']

 

Conclusion

You now know what the assert keyword does in Python and how to use it to check that values are true.

assert