How to Check Conditions with Assert () and Their Relationship with Exceptions in Python
Here we explain how to use assert in Python, but we recommend that you first read our other posts about exceptions and the use of try, except and finally.
Assert in Python
Assert is a question of the verification of a certain condition, if it is not true, then it will throw the exception AssertionError. Let's look at an example.
assert(1==2) # AssertionError exception is thrown
That is, if the existing content within assert is equal to False, the exception will be thrown. The same result could be achieved by doing the following. But wearing it assert() is more comfortable.
if condition: raise AssertionError()
We can also add a text with relevant information about it assert().
x = "Welcome" #if condition returns False, AssertionError is raised: assert x == "Hello", "x should be 'Welcome'"
You can also make use of assert() without using parentheses as shown below.
x = "wikhtp" #if condition returns True, then nothing happens: assert x == "wikihtp" #if condition returns False, AssertionError is raised: assert x == "wikipedia"
assert () in testing
assert() can also be very useful for writing unit tests or unit tests. Let's look at an example.
Imagine that you have a function calculate_mean() that, as its name suggests, calculates the mean of a set of numbers.
def calculate_mean(list): return sum(list)/len(list)
In the world of programming, it is very important to test or test software, to make sure it is free of errors. Thanks to the use of assert() we can carry out these checks automatically.
assert(calculate_mean([5, 10, 7.5]) == 7.5) assert(calculate_mean([4, 8]) == 6)
So if we make these checks part of our code, we could protect our function, making sure that no one "breaks" it.
assert() in functions
It can be useful to use assert() when we want to perform a check, such as within a function. In the following example, we have a function sum() that only adds the variables if they are whole numbers.
# Sum function of integer variables def sum(a, b): assert(type(a) == int) assert(type(b) == int) return a+b # Error, since variables are not int sum(3.0, 5.0) # Ok, the arguments are int sum(3, 5)
assert () with classes
Another example could verify that an object belongs to a certain class.
class MyClass(): pass class MyOtherClass(): pass my_object = MyClass() my_other_object = MyOtherClass() # Ok assert(isinstance(my_object, MyClass)) # Ok assert(isinstance(my_other_object, MyOtherClass)) # Error, my_object does not belong to MyOtherClass assert(isinstance(my_object, my_other_object)) # Error, my_other_object does not belong to MyClass assert(isinstance(my_other_object, MyClass))