Importance of ‘Assert’ in Python

Sometimes, a really useful part of a programming language doesn’t get as much attention as it should. That’s what happened to Python’s built-in assert statement – not many people talk about it, even though it’s quite handy. So, today we are going to give it a lot of importance!

Python’s assert statement is a handy tool for making sure your code is correct. Today we will explore what assert does in Python and how it can be useful. Basically, assert checks if something is true while your code is running. It has a simple way of writing it, and if the statement is false, it raises an exception.

As a Debugging Tool

Let’s understand this with an example! Imagine a scenario where you’re developing a pricing process for product, and you want to make sure that price should be a positive number and that’s why you added an assert statement to make sure that the user is entering the valid inputs. Below is the code that you might write-

class Product:
def __init__(self, initial_price):
assert self.initial_price > 0, "Invalid Price"
self.price = initial_price

def calculate_total_price(self):
total_price = self.price * 1.1 # Adding 10% tax
return total_price

Then next day, you came again for work and added a new method for applying the discount and calculate the final price.

class Product:
def __init__(self, initial_price):
self.price = initial_price
assert self.price > 0, "Invalid Price"

def calculate_total_price(self):
total_price = self.price * 1.1 # Adding 10% tax
return total_price

def apply_discount(self, discount_amount):
self.price -= discount_amount

You can see how you unknowingly introduced the bug. You did not validate the discount_amount which would raise an “AssertionError” if discount_amount value passed is greater than price.

That’s how ‘assert’ statement points out the bug in early development stage and helps you debug the code. Now you can fix your code before you move it to production.

Testing

In testing, the assert statement is a very important tool used to verify whether the actual results of a test match the expected results. When the asserted condition is true, the code continues to execute. However, if the condition is false, an AssertionError is raised, indicating that something unexpected has occurred. You can understand by below example-

import unittest

def calculate_total_price(cart_items, tax_rate):
subtotal = sum(item['price'] * item['quantity'] for item in cart_items)
total_price = subtotal * (1 + tax_rate)
return total_price

class TestCart(unittest.TestCase):
def test_price(self):
cart_items = [
{'name': 'Veggies', 'price': 20.0, 'quantity': 2},
{'name': 'Fruits', 'price': 15.0, 'quantity': 3},
{'name': 'Grains', 'price': 10.0, 'quantity': 1},
]

# there is always a tax
tax_rate = 0.08

# expected total price
expected_total_price = sum(item['price'] * item['quantity'] for item in cart_items) * (1 + tax_rate)

# actual total price using the function
actual_total_price = calculate_total_price(cart_items, tax_rate)

# Assert that the actual total price matches the expected total price
assert actual_total_price == expected_total_price, f"Expected {expected_total_price}, but got {actual_total_price}"

if __name__ == '__main__':
unittest.main()

When not to use?

  1. Data Validation – Though I gave the example of the same, but that is for debugging in development stage only. The assert statement should not be moved to the production in this case, because Assertions can be globally disabled by using the -O (optimize) command line switch when running the interpreter. When optimizations are enabled (using -O or -OO), all assert statements are removed from the compiled code.
    So, always remember to do your validation with if-statements and raise validation error if any!
  2. Error Handling – Assertions are not a substitute for proper error handling. If you turn off assertions in your final code, important error checks will be gone too.

Conclusion

I think Python’s assertions are a valuable debugging tool that many of us overlook. Knowing when and how to use assertions can improve the maintainability and debugging of your code significantly. Learning this skill can improve your Python expertise and save you countless hours of debugging.
Happy Learning!

Leave a comment