Testing and debugging are crucial when it comes to building a code and maintaining it. While they are used on a large scale in developing and making projects in the industry, we also use them daily on a small scale.
When we have any potential error in the code that can cause the execution to work unexpectedly, we use debugging to trace that error(exception) and make it right.
Many testing modules and approaches in Python can be applicable in different use cases.
Learn about the Python unit test module here
Assert is one such keyword, which can be used to debug the code by determining if a condition is True. We are going to understand this keyword and use it to validate the type of variables found in our code.
In Python, assert is used to validate conditions, raising an AssertionError if the condition is false. It’s effective for debugging, especially for type checking. Combining assert with isinstance enhances type validation, ensuring variables match expected data types
Understanding the Assert Keyword
Assert is used for checking the truth value of a statement. If the condition is True, the following statements(conditions) are executed but if it is False, an error is raised. AssertionError is the error raised by this keyword.
Let us see an example of usage.
def divideab(a, b):
assert b != 0, "Division by zero is illegal!"
return a / b
res= divideab(10, 2)
print(res)
The function divideab
is used to perform the division of a number(a) by another number (b). The assert keyword is used to ensure that the denominator is not zero. The result of calling this function for a=10 and b=2
is stored in res. The output is 5 since the denominator is not zero.
Now what if the denominator is zero?
def divideab(a, b):
assert b != 0, "Division by zero is illegal!"
return a / b
res = divideab(10, 2)
print(res)
res2 = divideab(10, 0)
print(res2)
The new variable res2 is used to store the result of the division of 10 by zero.
def divideab(a, b):
assert b != 0, "Division by zero is illegal!"
return a / b
res = divideab(10, 2)
print(res)
res2 = divideab(10, 0)
In addition to the previous condition, we have also added the statement which might lead to AssertionError.
One thing we should note is that any statement after the potential snippet that can raise an AssertionError will not be executed.
print("Hello")
def divideab(a, b):
assert b != 0, "Division by zero is illegal!"
return a / b
res = divideab(10, 2)
print(res)
res2 = divideab(10, 0)
print("Hello World")
Now that we have understood the Assert statement and the error associated with it, let us see the two approaches to using this keyword to validate the type of variables.
Validating Variable Types with Assert
Follow the example below to know how to use the assert keyword to determine the type of variable in the code.
x = 42
assert type(x) is int, "Variable is not of type int!"
print(True)
For starters, a variable called x is initialized with a value of 42. Then we use the assert keyword to determine if the type of the variable x is int or not. If the type is int, True is printed else, the error statement Variable is not of type int! is displayed on the screen.
Let us see when the error message is printed in the same example.
x = 42
assert type(x) is str, "Variable is not of type string!"
print(True)
In this case, we have assigned the datatype str
to the variable x. Let us see how this code executes.
Combining Isinstance and Assert for Type Checking
In the second approach, we are going to use the instance keyword along with the assert statement to determine the right type of variables.
The isinstance keyword is used to check if the object given is of the mentioned type. It returns True if the object is of the specified type, else returns False.
Syntax of isinstance method:
isinstance(object, type)
Let us see an example.
y = "Hello World"
isinstance(y, str)
The variable y has an input called Hello World. In the next line, we are trying to determine if the type of y is a string with the help of isinstance
.
Now let us see how we can use assert with this keyword.
y = "Hello World"
assert isinstance(y,str)
print(True)
assert isinstance(y, int), " y is not of type int"
We have taken the same example and added the assert keyword before the instance. The first condition is True as we know Hello World
is a string. In the second assert statement, we have used Integer as the type of y, which is not true so AssertionError is raised.
Wrapping Up: Insights on Assert and Isinstance in Python
To put it there simply, the assert keyword is used as a debugging tool, where the validity of a condition is verified, also allowing the inclusion of any statements to pass when the condition is False. It might sound similar to the Try-Catch block, albeit they are different. While the try-catch block is used to catch a potential exception in the snippet that might interrupt the execution, the assert keyword is used to determine the validity of a condition.
We have seen a demonstration of the assert keyword and used it to test the suitable data type for different variables. Following this, we have also used another special one(isinstance) to determine the right type of the variable.