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.
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 ...