Assertions are used to make sure that certain conditions are met and that the program execution is proceeding as expected. They are meant for verifying program correctness and upholding assumptions made in the program. This makes them useful for debugging and testing purposes as they allow you to monitor variables and invariants at different stages of execution.
In Python, we use the assert
keyword to create assertion statements. The keyword , checks whether a condition evaluates to True
or False
, it throws an AssertionError
if False
.
The syntax of the assert
statement is as shown below:
assert <condition>, <message>
copy
The condition
is tested, if it evaluates to True
, nothing happens, if it evaluates to False
, an AssertionError
exception is raised.
The message
which is optional, is a string that will be displayed with the AssertionError
exception as the error message.
Assert-usage and examples
In the above example, we defined a function to divide two numbers. The assert
statement is meant to verify that the value of b
is not equal to 0
in which case the division operation would be undefined.
In the following example, we specify a message in the assert
statement that will be displayed if the assertion fails.
Catching an AssertionError exception
The AssertionError
exception can be handled just like any other exception including by use of the try/except
statement. We can, put the code that may raise an AssertionError
in a try
block, then put the code that should run if an AssertionError
is raised in the corresponding except
block.
In the above example, we used the try/except
statement so that when an AssertionError
is raised, we display a friendly message rather than the message crashing as it normally would.
Note that the assert
statement is normally used for debugging and testing purposes. It is meant to perform sanity checks to ensure that the program behaves as expected. It is therefore mostly suitable in a development environment not for production.