Assertions in Python

Assertions In Python Title

Let us learn about a commonly used testing and debugging technique called Assertions in Python. We will learn what assertions are, why they are used, when not to use them, and their syntax. So let’s get started.

What are Assertions in Python?

Assertions in Python are statements that are used to assert a condition on the program. They are designed in a way that if the asserted condition turns out to be false, the program will not continue.

If the asserted condition is false, the statement raises an AssertionError.
You have the option to send a message along with the AssertionError exception.

Why are Assertions Used?

Assert statements are used by the programmer to test and debug code during the development cycle and notify the programmer of any bugs that may be present in the code.

These statements are meant only for the developer as assert statements are a part of testing and debugging the code.

So, to ensure that certain conditions are met before or after the execution of blocks so that logical errors and exceptions can be avoided later in the program, we use assertions.

The intended use of the assert statement is that the condition you write in the statement is never supposed to be false. If the condition does turn out to be false, it is supposed to be a bug in the program which must be removed.

A good example of assertions can be to ensure that a function that calculates the anti-logarithm of a number always gives a positive result, if it happens otherwise, then the fault is in the logic of the function and not the input or any other external factor.

When Not to Use Assertions?

Assertions are not supposed to handle run-time errors.

Errors like “File not found“, “Insufficient memory/heap“, “Connection not established“, etc. can be handled and rectified in the else-clause or the except-clause.

These statements are not bugs, but simply exist because of some external factor not being met, and the program is probably fine by itself.

Because assertions are debugging instructions, if the program is run in optimized mode then all assertions are ignored during the execution of the program.

To run a program in optimised mode we use the -O flag as follows:

python -O file_name.py

This will disable debugging for the code, and all assert statements will be ignored.

So if any assertion is used to validate input or a security issue, then its validation no longer exists in optimised mode, and that can lead to unwanted errors and security loopholes.

E.g., if you use assertions to assert that the user is an admin, and give them admin privileges, then one can simply run the code in optimized mode, and the assertion will be ignored, giving all users admin privileges.

Similarly, if you use assertions to verify that a user’s age is more than 18, then if the code is run in optimized mode, any user can bypass the assertion.

It all goes to say that if a condition is the result of a bug in the program itself, i.e., there is something wrong in the code, not in the input or external conditions, then assertions are used to assert the condition so that the existence of the bug can be established.

Implementing Assertions in Python

Let us take a few examples to understand how to write assertions in Python.

Note that the code samples are very basic examples and only serve the purpose of explaining the syntax and working of the statement.

a = 12
b = int(input())
assert b != 0
print(a / b)

In the above code, we are asserting the condition that b cannot be zero before going to the next statement.

Let us look at the syntax before going to the output.

The keyword assert must always be followed by an expression that will result in True or False. We also have the option to add a message, but we’ll see that later.

In the above case, if the input is anything but 0, the expression will result in True and the output will look like this:

Assertion Passed Example
Assertion example when condition is satisfied

Here, we gave 5 as the input, and the code ran without any problems.
Now let us see what happens when we give 0 as the input:

Assertion Failed Example
Assertion example when condition is not satisfied

When b has a value of 0, the condition returns False, and the statement raises an AssertionError.

This is like any other exception, and it can be handled in a try-except-clause, however, doing so defeats the purpose of assertions, as they are supposed to notify the programmer of a possible bug in the program.

Let us add a message to the assertion:

a = 12
b = int(input())
assert b != 0, "The input cannot be zero!"
print(a / b)

Here again, we are asserting the condition that b cannot be 0, and if the condition is false, the assertion will give an AssertionError along with a message.

So, to give a message along with the exception, we need to specify a string containing the message after writing the condition and separating the condition and message with a comma.

For a non-zero input, the output won’t have any changes, but if the input is 0, then the output will look like this:

Assertion Message Fail Example
Assertion fail with a message

Notice that the exception is followed by an error message that we specified.
Assert statements should always have a message to understand which assertion failed if you have multiple assertions.

Conclusion

In this tutorial, we learned what assert statements are, we discussed when to use them and when not to use them. We then saw how they are written in Python and how they can help with debugging your code.

I hope you learned something, and see you in another tutorial.