This is an archived version of the course and is no longer updated. Please find the latest version of the course on the main webpage.

Assert

Python also offers the assert keyword. This can be used to enforce certain conditions in your code.

assert will check whether an expresion returns True.

If it is True, it will not do anything.

If it is False, then an AssertionError will be raised.

It is mainly a debugging aid to make sure that certain conditions do not happen. If they do happen, then there is definitely a bug in your code! So, in a way, you are performing testing directly in your code.

For example, in your machine learning experiments, you might want to use assert to make sure that you have the same number of feature vectors x_train as the output labels y_train.

assert len(x_train) == len(y_train)

If this test fails, then something is wrong with your code somewhere, so you should check! This will help you pinpoint your problem.

You can also include an error message to include as argument to the resulting AssertionError instance.

assert len(x_train) == len(y_train), "x_train must have the same length as y_trian"
## AssertionError: x_train must have the same length as y_train

Of course, you can handle the AssertionError as with all Exceptions with a try ... except block.

Assertion is also often used at the start of a function to make sure that the input arguments are valid. For example:

import numpy as np

def factorial(number):
    assert (number > 1), "Number must be greater than 1"
    return np.prod(range(1,number+1))

print(factorial(1))  ## AssertionError: Number must be greater than 1
print(factorial(-5)) ## AssertionError: Number must be greater than 1
print(factorial(5))  ## 120

Try playing around with assert statements yourself. For example, try something like assert 3==5 or assert 5==5 and see what happens (or not!)