Using assert for testing#

The Python assert statement means - “raise an error unless the following expression is equivalent to True”.

By “equivalent to True”, we mean the expression returns True from Python truth value testing.

assert raises an AssertionError if the statement is equivalent to False. It does nothing if the statement is equivalent to True.

So, if you assert an_expression and there is no error, then the result of an_expression was equivalent to True. The following expressions evaluate to True, and therefore the asserts do not raise an error:

# No errors here.
assert True
assert 10 == 10
assert 10 % 2 == 0

These expressions are equivalent to False, and the asserts do raise errors:

# Raises error
assert False
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
Cell In[2], line 2
      1 # Raises error
----> 2 assert False

AssertionError: 
# Raises error
assert 10 == 11
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
Cell In[3], line 2
      1 # Raises error
----> 2 assert 10 == 11

AssertionError: 

Although assert does work with expression values of True and False, the test that assert uses is more general than expr_result == True. In fact, assert uses truth value testing to decide whether to raise an AssertionError or not:

# No error
assert ['some', 'elements']  # not-empty list tests as True
# Error
assert []  # an empty list tests as False
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
Cell In[5], line 2
      1 # Error
----> 2 assert []  # an empty list tests as False

AssertionError: 
# No errors
assert 10  # any number other than zero evaluates as True
assert 1
# Error
assert 0
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
Cell In[7], line 2
      1 # Error
----> 2 assert 0

AssertionError: 
# Error
assert None
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
Cell In[8], line 2
      1 # Error
----> 2 assert None

AssertionError: 

Warning

Note that assert should not be used in order to raise errors at runtime.

The use cases for assertions are development, testing and debugging your code, and are for declaring “This condition is expected to be to true”. If this always succeeds during testing, it is considered safe to remove in production.

If Python is run with optimization, assert statements will be removed for speed, and you as the developer do not control whether your code is run with optimization or not.

For error conditions that you expect to encounter in runtime, raise exceptions.