In this article, we'll examine how to use the assert
statement in Python.
In Python, the assert
statement is used to validate whether or not a condition is true, using the syntax:
assert <condition>
If the condition evaluates to True
, the program continues executing as if nothing out of the ordinary happened. However, if the condition evaluates to False
, the program terminates with an AssertionError
.
>>> assert True
Nothing happens when the code above is executed, since the condition evaluates to True
. Alternatively, the condition in the example below evaluates to False
:
>>> assert False
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
For added clarity, we can add a custom error message to the assertion output as follows:
>>> assert False, "This is a custom assertion message!"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: This is a custom assertion message!
The assert statement is useful when we want to check that a variable in our code assumes the correct value and terminate the program if it doesn't. This helps prevent silent failure modes, which can occur if the program continues executing with erroneous values and can be difficult to debug.
Here is an example of an assert statement with a more meaningful condition. Let's assume that we want to ensure that a flag variable input by the user has been set to one of several correct values. If not, we will terminate execution of the program. We can do that as follows:
>>> flag = input("Enter a flag (y/n): ")
Enter a flag (y/n): y
>>> assert flag == "y" or flag == "n", "Invalid flag, must be 'y' or 'n'"
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
In the above example, the user inputted a valid value for the flag, so no errors are thrown. However, in the example below, an assertion is thrown due to invalid user input:
>>> flag = input("Enter a flag (y/n): ")
Enter a flag (y/n): b
>>> assert flag == "y" or flag == "n", "Invalid flag, must be 'y' or 'n'"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: Invalid flag, must be 'y' or 'n'
When used in this way, your code should catch the thrown error and show the custom error message as output to the user so they can correct their response. This has a huge number of uses in Python programs, whether it be asserting inputs to an API route or checking that a downloaded resource contains the proper information.
Another important point to note is that when you're running the Python interpreter or Python script from the command line, the –O
flag can be used to run the program without enforcing any assertions. This will ignore the assert statements by turning off the Python interpreter's debug mode. Be careful using this as it can lead to your code accepting invalid or dangerous inputs.
About the Author
This article was written by Jacob Stopak, a software consultant and developer with a passion for helping others improve their lives through code. Jacob is the creator of Code Card - a convenient tool for developers to look up, copy, and paste common code snippets.