Assert Statement in Python
In programming assertions are used to verify whether a specified condition is true or not. For example if we have a function to add two numbers, before using the
+ operator to add the two numbers provided by user, we can use an assertion to check if the values input are numbers only and not alphabets or special characters.
Assert statement contains a Boolean expression that checks for trueness of a condition and returns true if found valid else returns false.
When an Assertion is used in a program, then in case of positive assertion the program will continue its execution normally whereas in case of negative assertion the program will stop its execution and throw an error.
In python there is a built-in assert statement which can be used to implement assertions in your program. The assert statement in python takes a condition or an expression as an argument and expects it to be true for the program to continue its execution. If the condition/expression is false, the assert statement will throw an AssertionError, which as a result interrupts the normal execution of the program.
Assertion in python is the pythonic way of applying conditions for validations where usually
if...else conditions are used.
Let’s take a simple example to understand when and where to use assert statement. If you have a program to take Password as input from a user where the input should be checked whether it’s a strong password and if found strong it should be stored, else the user should be asked to re-enter the password. In this case we can use an assert statement to apply various conditions to the input password value to check if it’s a strong password. If the conditions return true then the program will continue to store the password else the assert statement will throw an AssertionError. Makes sense!
Syntax of the
Assert statement can be declared in two ways:
assert <condition> # with condition and error message assert <condition>, <error message>
In the first type of syntax, the assert statement will only check the condition and when the condition will be false it will raise an assertion error. But in the second case, assert statement will also print a message along with assertion error when the condition is false.
Time for an example!
Let’s take a simple example where we will be defining a function to find percentage of marks scored where a list of marks scored out of 100 will be provided. We will be using assert statement to make sure no marks entry in the list contains negative marks.
As you can see in the program above, when we provide 1 negative value the program fails with an AssertionError, else it executed successfully and returns the result.
Now lets update the above program to include a message in the assert statement to be shown along with the assertion error.
# function to calculate percentage, given a list of marks
out of 100 def percentage(marks): for m in marks: # marks should always be a positive value assert m > 0, "Only positive values allowed" return (sum(marks)/len(marks)) print(percentage([90,93,99,95,-94]))
Traceback (most recent call last): File “/tmp/sessions/2ce06e6f313b60f6/main.py”, line 8, in print(percentage([90,93,99,95,-94])) File “/tmp/sessions/2ce06e6f313b60f6/main.py”, line 5, in percentage assert m > 0, “Only positive values allowed” AssertionError: Only positive values allowed
Some important points to remember!
Assert is not same as try…except. try…except is used for dealing with a recoverable error which can be followed by a corrective measure while assert statement is used for the errors which either can’t be recovered or any corrective measure is not required for them.
Assert is a statement not a function, hence never use it with parentheses. If you try to execute the following
assert(condition, message), assert will execute with a tuple as the first argument. It will take
(condition, message) as a tuple input.
The behaviour of an assert statement is like the following code:
if not condition: raise AssertionError()
Although it is not entirely this but more or else behaves like this.
If you have a program with many assert statements and you want to disable all the assert statements, run the python script in optimized mode which can be done using the
python -o yourscript.py
Because in optimized mode
__debug__ is false and as per the official documentation of python, assert statement is equivalent to:
if __debug__: if not expression: raise AssertionError
__debug__ is false, assert statements are disabled.