codewithjohn.dev
Published on

Asserting Your Code: A Guide to Python Assert Statement

Python is one of the most versatile programming languages, known for its simplicity and readability. One of the key features that contribute to Its robustness is the assert statement. The assert statements can be useful when testing and debugging. The easiest way to think of an assertion Python is a way to make sure or assert certain conditions that you expect to be true at a specific point in your code.

The syntax of an assert statement is as follows:

assert condition
assert condition, error_message
  • condition is the expression that is being tested
  • error_message is an optional string that provides a custom error message to be displayed when the assertion fails.

in python assert takes a condition and raises an AssertionError if the condition evaluates to False. If the given condition evaluates to True then it continues to execute next statements.

Here's an example that demonstrates a simple assert statement.

example_one.py
def divide(a, b):
    assert b != 0, "Divisor cannot be zero!"
    return a / b

print(divide(10, 2))  # Output: 5.0
print(divide(10, 0))  # AssertionError: Divisor cannot be zero!

In the above example, we used the assert statement to check If the value of Divisor b is not equal to zero, we also provide a custom error message. In the first function call, the condition evaluated as True, so the function passes the assert statement and returns the expected value. but in the second function call The condition is evaluated as False, so an assertion error is raised with the custom error message.

Here's a second example that demonstrates assert statement.

def calculate_area(length, width):
    assert isinstance(length, (int, float)), "Length should be a number!"
    assert isinstance(width, (int, float)), "Width should be a number!"
    assert length > 0 and width > 0, "Length and width should be positive!"

    return length * width

print(calculate_area(5, 10))  # Output: 50
print(calculate_area(-5, 10))  # AssertionError: Length and width should be positive!
print(calculate_area(5, "10"))  # AssertionError: Width should be a number!

In the above example we are checking if the length and the width are both type of number and positive if not assertion error will raised with the provided custom error message.

The AssertionError on of the built-in exception that can be handled using the try-except block let us demonstrate this using the first example.

example_three.py
def divide(a, b):
    assert b != 0, "Divisor cannot be zero!"
    return a / b

try:
  divide(10, 0)
except AssertionError as msg:
  print(msg) # Output: Divisor cannot be zero!!

In the above example calling divide(10,0) will raise an AssertionError because the condition evaluated as False which will be handled by the except block.

Conclusion

The assert statement in Python is a powerful tool that helps developers identify and fix issues during the development process. By using assert statements, you can validate assumptions, test function inputs and outputs, and ensure expected results.