Are you a programmer? If so, debugging is an essential skill, irrespective of the language you’re coding in. In this article, you will learn how to use the assert statement in Python for effective debugging.

When you’re working on a project, you’ll define multiple modules. This includes functions, class definitions, and more. And you’ll likely run into errors or unexpected results because of a bug in the implementation. Assert statements are helpful in debugging such code.

In this tutorial, we’ll learn the syntax to use the assert statement followed by code examples to see it in action. We’ll also see what assertion errors are and how we can use them to fix the errors in code during development.

Let’s begin!

How to Use the Assert Statement in Python

We’ll learn the syntax to use the assert statement, then proceed to code some examples.

Syntax of the Assert Statement

Let’s start with the syntax to use the assert statement in Python:

assert expression, message

Here,

  • expression is any valid Python expression to be evaluated. This can be a condition on the value of variable, truth value of variable, return value from a function, and more.
  • So long as the expression evaluates to True, the assert statement does not throw an error or return anything. This indicates that the program works as expected.
  • If the expression is no longer True, an AssertionError exception is raised.
  • message is an optional string. You can specify a message that gets displayed in the trace back whenever an AssertionError exception is raised.

Next, let’s proceed to code a few examples where the assert statement can help us write cleaner and bug-free code.

You can find the code examples used in this tutorial in this GitHub gist.

Python’s Assert Statement Examples

<img alt="Pythons-Assert-Statement-Examples" data- data-src="https://kirelos.com/wp-content/uploads/2023/03/echo/Pythons-Assert-Statement-Examples.png" data- decoding="async" height="294" src="data:image/svg xml,” width=”400″>

Consider the following example. Say you have a discount variable in your code. But you’d like its value to be always less than or equal to the max_discount.

To check that you accidentally don’t set the discount variable to a value, you can add an assertion. The expression to evaluate is: discount <= max_discount.

>>> max_discount = 50
>>> discount = 20
>>> assert discount <= max_discount

Here, discount (20) is less than max_discount (50). So the assert statement does not throw any error.

The AssertionError Exception

If the discount variable is set to a value greater than max_discount, an AssertionError exception is raised.

>>> discount = 75
>>> assert discount <= max_discount
Traceback (most recent call last):
  File "", line 1, in 
AssertionError

We know that the assert statement also allows us to specify an optional message string.

Let’s also use a message string that gives a more descriptive diagnostic info. To the assert statement, let’s add a Python f-string that also contains the values of discount and max_discount.

>>> assert discount <= max_discount, f"discount should be at most {max_discount}; got discount = {discount}"
Traceback (most recent call last):
  File "", line 1, in 
AssertionError: discount should be at most 50; got discount = 75

As seen in the output cell above, the AssertionError exception now includes the values of the discount and max_discount variables.

Debugging and Testing Python Functions with Assert

When defining functions, you may sometimes inadvertently introduce bugs (logical errors) that will prevent your function from working as intended.

<img alt="Debugging-and-Testing-Python-Functions-with-Assert" data- data-src="https://kirelos.com/wp-content/uploads/2023/03/echo/Debugging-and-Testing-Python-Functions-with-Assert.png" data- decoding="async" height="688" src="data:image/svg xml,” width=”1478″>

Let’s take an example. Suppose there’s a test in a class and the students are given a chance to attempt a bonus question. Any student who attempts the bonus question will get 10 additional marks in the test. 😄

Consider the following function get_final_score:

  • It takes in a current score, score, and a Boolean bonus
  • If a student has answered the bonus question, the Boolean bonus is True, and they get 10 points more than their current score.
  • The function then returns the final score.
def get_final_score(score,bonus):
    if bonus:
        score  = 10
    return score

Let’s make a few calls to the function. We see that for scores of 34 and 40 with bonus set to True and False, the final scores are 44 and 40, respectively.

print(get_final_score(34,True))
# 44
print(get_final_score(40,False))
# 40

However, the maximum points on the test is, say, 50. So if a student scores 49 and has also answered the bonus question, the function get_final_score will happily compute the final score to be 59.

print(get_final_score(49,True))
# 59

Technically, it’s possible. But let us assume that a student cannot score more than the maximum possible points for the test. 🙂

So let’s initialize a max_score variable. And capture the returned score from the function in the final_score variable.

Subsequently we add an assertion that checks if the final_score is less than the max_score.

def get_final_score(score,bonus):
    if bonus:
        score  = 10
    return score

final_score = get_final_score(47,True)
max_score = 50

assert final_score <= max_score

We now get an AssertionError exception for the function call get_final_score(47,True):

Traceback (most recent call last):
  File "main.py", line 17, in 
    assert final_score <= max_score
AssertionError

Now we add a descriptive f-string to the Python assert statement:

assert final_score <= max_score,f"final_score should be at most {max_score}; got {final_score}"
Traceback (most recent call last):
  File "main.py", line 17, in 
    assert final_score <= max_score,f"final_score should be at most {max_score}; got {final_score}"
AssertionError: final_score should be at most 50; got 57

Modifying the Function

Let’s go back and modify the definition of the get_final_score function to fix the unexpected behavior:

  • The function get_final_score also takes max_score as a parameter.
  • We check if bonus is True. If True, we add 10 points to the score variable.
  • Then, we check if score is greater than max_score. If so, we return max_score.
  • Otherwise, we return score.

We’ve now ensured that the final score is always less than or equal to max_score.

def get_final_score(score,bonus,max_score):
    if bonus:
        score  = 10
    if score > max_score:
        return max_score
    return score

As a quick exercise, write a few assertions to confirm that the function now works as expected.

A Note on AssertionError Exception

Though an AssertionError exception occurs when the expression evaluates to False, we should remember to not handle such errors as exceptions. Meaning we should not do something like this:

try:
    
except AssertionError:
    

In the previous example on get_final_score, we used the assertion to check if final_score is less than max_score. Then we modified the function definition such that there are no assertion errors.

That’s what assertions are for. They are sanity checks for code, and help in writing cleaner code. Exception handling, on the other hand, is to anticipate and handle unexpected errors at runtime. These often include invalid input types and values.

To sum up, you should use Python assert statement for effective debugging and not handle AssertionErrors as exceptions.

Conclusion

This tutorial helped you understand how to use assert statement in Python. Here’s a summary of what you’ve learned:

  • Python assert statements (assertions) take the form assert expression. This checks if the expression is True. If it does not evaluate to True, an AssertionError exception is raised.
  • You can also use the assert with the syntax assert expression, message. This will print out the message string whenever an AssertionError exception occurs.
  • You should remember not to implement exception handling to handle assertion errors. And use assertions as a helpful debugging tool for sanity checks of your code.

As a developer, assertions help you with debugging. To ensure all the individual components (modules) of the project work as expected, you can learn how to write unit tests in Python.

Next, check out this list of beginner Python projects you can work on.