Search⌘ K
AI Features

Assertions and Validation

Explore how to use assertions to catch internal logic errors and validation to manage external input safely. Understand when and why to fail fast and loudly to maintain program integrity and create more reliable Python applications.

As systems grow more complex, data moves through functions in ways that are not always obvious. If invalid data is allowed to propagate silently, it can corrupt program state or trigger confusing failures far removed from the original mistake.

Defensive programming addresses this risk by encouraging programs to fail fast and fail loudly. When something “impossible” occurs, the program should immediately signal the problem rather than continuing in an invalid state. This approach allows us to identify and fix the root cause quickly, instead of chasing subtle bugs long after the damage has been done.

The assert statement

Python provides a built-in tool for debugging and sanity checks called the assert statement. An assertion acts as a checkpoint in the code where we declare an assumption, e.g., “I claim this condition must be true.” If the condition evaluates to True, the program continues executing normally. If the condition is False, Python immediately stops execution and raises an AssertionError, signaling that an unexpected situation has occurred.

The syntax is straightforward:

assert condition, optional_message

Assertions are most useful during development to catch logical errors early, helping programs fail earlier when assumptions are violated.

Python
def calculate_discounted_price(price, discount):
# We assert that the calculation inputs make sense for our internal logic
assert 0 <= discount <= 1, f"Discount {discount} must be between 0 and 1"
final_price = price * (1 - discount)
# We assert the result is logically consistent
assert 0 <= final_price <= price, "Final price cannot be negative or greater than original"
return final_price
# This runs successfully
print(f"Price: {calculate_discounted_price(100, 0.2)}")
# This triggers an AssertionError immediately
print(f"Price: {calculate_discounted_price(100, 1.5)}")
  • Line 3: We establish a precondition for the function. By enforcing that the discount is a percentage between 0 and 1, we guarantee the formula below receives valid ...