Assertions in Python
An assertion in Python is a powerful debugging tool that we can use to display diagnostic information while testing or running a program.
It helps to validate assumptions within the program code so that we can identify errors swiftly and effectively. We can perform assertions using assert statement in Python.
When the Python interpreter encounters an assert statement in the program, it evaluates the accompanying expression. If the result of the expression is evaluated to False, Python raises an AssertionError exception.
There are the following areas where we can use assertions in Python:
- To check a valid input or a valid output.
- In checking the output of the functions.
- Can be used for testing the program code.
- To check the values of arguments.
Assert Statement in Python
Python provides an inbuilt assert statement that we can use in the program for assertion conditions. The assert statement in Python allows us to use debugging code in the program and ensuring that certain conditions are met or not during the execution of a program. It is a simple statement with the following general syntax:
assert condition, message # assert statementIn the above syntax, assert is a keyword that is followed by a condition and message. The condition in the assert statement is a boolean expression that evaluates to true or false.
If the condition evaluates to true, assert statement does nothing. If the condition evaluates to be false, the assert statement raises an AssertionError exception that we can catch and handle like any other exception using try-except statement.
But, if not handle, it will terminate the program and generate a traceback. The ‘message’ parameter is optional string and provides additional information about the assertion.
Python translates the assertion statement internally this code:
if __debug__:
if not condition:
raise AssertionError(message)
In the above internal code, a __debug__ is a built-in read-only variable that is 1 (True) by default. When assertions are enabled ( i.e. __debug__ flag is True), Python performs this translation and raises an AssertionError exception if the condition evaluates to False.
Example Program based on Assertions in Python
Let’s take some simple example programs based on the assertions in Python.
Example 1:
# Simple Python assertions
x = 5
# Assert statement with error message.
assert x == 5 # assert statement
print("Assertion passed successfully!")
Output:
Assertion passed successfully!
In this example, the assertion condition x == 5 holds true, no AssertionError will be raised. The assert statement doesn’t produce any output by itself unless the assertion fails, in which case it raises an AssertionError exception. Since the condition x == 5 is true, the code runs smoothly, and the message “Assertion passed successfully!” is displayed on the console.
Example 2:
def calculate_discount(price):
# Assert statement with message.
assert price > 0, "Price should be greater than zero"
# Rest of the code
return price * 0.9 # Applying a 10% discount for demonstration purposes
# Outside of method definition.
# Call the function by passing an argument value and store it in a variable.
discounted_price = calculate_discount(70)
print("Discounted price:", discounted_price)
Output:
Discounted price: 63.0
In this example, we have called the calculate_discount() function with passing an argument value 70. The assert statement will check the assertion (i.e. coitional expression) price > 0. Since the value 70 is greater than 0, the assertion passes without raising an AssertionError exception.
This example demonstrates how we can use assertions to validate conditions within functions in Python. If the condition in the assertion fails (e.g., if we call calculate_discount with price = 0), it would raise an AssertionError with the message “Price should be greater than zero”. Look at the below example code.
Example 3:
def calculate_discount(price):
# Assert statement with message.
assert price > 0, "Price should be greater than zero"
# Rest of the code
return price * 0.9
# Outside of method definition.
# Call the function by passing an argument value 0 and store it in a variable.
discounted_price = calculate_discount(0)
print("Discounted price:", discounted_price)
Output:
Traceback (most recent call last):
File "C:\Python Project\Program.py", line 9, in
discounted_price = calculate_discount(0)
File "C:\Python Project\Program.py", line 3, in calculate_discount
assert price > 0, "Price should be greater than zero"
AssertionError: Price should be greater than zero
Let’s take an example program in which we will catch and handle an AssertionError exception using try-except block.
Example 4:
def divide_numbers(a, b):
try:
# Assert statement with error message.
assert b != 0, "Division by zero is not allowed"
result = a / b
print("The result of", a, "divided by", b, "is:", result)
except AssertionError as e:
print("AssertionError:", e)
# Calling function.
divide_numbers(10, 2)
divide_numbers(8, 0)
Output:
The result of 10 divided by 2 is: 5.0
AssertionError: Division by zero is not allowed
In this example, the divide_numbers() function attempts division in the try block. If the assertion (b != 0) fails (i.e., attempting to divide by zero), it raises an AssertionError. The except block catches this error, allowing us to handle it gracefully by displaying an error message.
Different Types of Assertions in Python
There are different types of assertions in Python that we can use to check various conditions and validate assumptions. Some commonly used types of assertions are as follows:
- Value assertions
- Type assertions
- Collection assertions
- Exception assertions
- Boolean assertions
1. Value Assertions:
Value assertions, also known as simple assertions, are used to validate that a specific value meets a certain condition or criteria. We use these assertions for debugging and testing purposes. For instance, ensuring a variable being used in the program holds an expected value. If an assertion fails, an AssertionError is raised. Here’s an example:
Example 5:
x = 10
assert x == 10, "x should be equal to 10"
print("Assertions passed successfully!")
Output:
Assertions passed successfully!
In this example, the assertion checks if the variable x contains the value 10. If the condition is true, the program continues execution. However, if x is not equal to 10, an AssertionError is raised, displaying the specified message: “x should be equal to 10”.
2. Type Assertions:
In Python, we can use type assertions to validate the type of a variable or value. Type assertions ensure that the expected data type is matched, otherwise, an AssertionError exception is raised. They are especially useful when working with dynamically typed languages like Python, where the type of variable can change. Look at the below example code based on it.
Example 6:
value = 10
assert isinstance(value, int), "value should be an integer"
# If the assertion passes, the code continues here
print("The value is an integer:", value)
Output:
The value is an integer: 10
In this example, the isinstance() function checks whether the variable value is of type int. If the assertion holds true (meaning value is an integer), the program proceeds to the next line and displays “The value is an integer: 10”. However, if value is not an integer, an AssertionError is raised, displaying the specified message: “value should be an integer”.
3. Collection Assertions:
In Python, we use the collection assertions to validate properties or elements within collections, such as lists, tuples, sets, or dictionaries. These assertions allow us to evaluate that a collection contains a specific element or satisfies certain conditions or not. Here’s an example code:
Example 7:
numbers = [1, 2, 3, 4, 5]
assert 3 in numbers, "3 should be in the list"
# If the assertion passes, the code continues here
print("The number 3 exists in the list.")
Output:
The number 3 exists in the list.
In this code, the assert statement checks if the element 3 exists in the numbers list. If the element 3 is found in the list, the program control proceeds to display “The number 3 exists in the list.” However, if 3 is not in the list, an AssertionError would be raised, displaying the specified message: “3 should be in the list.”
4. Exception Assertions:
We use the exception assertions in Python to check whether a specific exception is raised or not within a piece of code. Exception assertions are generally used in unit tests to ensure that exceptions are caught and handled correctly in code or not. Here’s an example:
Example 8:
def divide(a, b):
try:
result = a / b
except ZeroDivisionError as e:
raise AssertionError("Division by zero not expected") from e
# Testing the exception assertion
try:
divide(10, 0)
except AssertionError as e:
print("AssertionError:", e)
else:
print("No AssertionError raised")
Output:
AssertionError: Division by zero not expected
In this example, the divide function() attempts to perform a division operation. If the divisor (b) is zero, it raises a ZeroDivisionError. However, within the except block, an AssertionError is explicitly raised using raise AssertionError(“Division by zero not expected”).
The program then tests this exception assertion by calling divide(10, 0). Since division by zero raises a ZeroDivisionError exception, the except block catches it and raises an AssertionError as specified.
5. Boolean Assertions:
In Python, we use the boolean assertions to validate the truthiness of a condition or expression. Boolean assertions ensure that a given condition or expression evaluates to True, otherwise, if false, an AssertionError exception is raised.. Here’s an example code:
Example 9:
value = 10
assert value > 0, "Value should be greater than zero"
# If the assertion passes, the code continues here
print("The value is greater than zero:", value)
Output:
The value is greater than zero: 10
In this code, the assert statement checks if the variable value is greater than zero. If the value is greater than zero, the program displays a message “The value is greater than zero: 10”. However, if value is not greater than zero, an AssertionError would be raised, displaying the specified message: “Value should be greater than zero”.
Best Practices to Use Assert Statement in Python
When using the assert statement in Python, there are some key points that you should follow for the best practices to ensure efficient usage. They are as follows:
- Use assert statement for debugging purposes and validating assumptions during development. It helps to catch errors and provides feedback on unexpected conditions. We can disable assertions in the code to avoid unnecessary performance overhead.
- Always try to keep assert statement simple and straightforward that can be easily understood.
- Avoid complex or lengthy expressions within assertions.
- While using assert statement in the program, provides clear and informative error messages that describe the cause of assertion failure so that the debugging process speeds up.
- Disable Assertions in production code for performance optimization.
- Enable assertions while running tests. It enables us to catch potential issues and validate the correctness of our code during the testing phase.
- Use assertions to document assumptions within the code that explicitly states assumptions and expectations.
- Don’t use assertions for input validation and error handling. Always do explicit input validation and handle potential errors appropriately.
By following these best practices, you can effectively use assert statement in Python program, simplifying debugging, and documentation, and ensuring code correctness during the development and testing phases.
In this tutorial, we have explained assertions in Python with the help of various examples. Hope that you will have understood the basic concept of using assert statement in Python and practiced all example programs.
Thanks for reading!!!



