When programming, there are “preconditions that must absolutely be true if the program is operating correctly,” such as “the variable at this point must be a positive value” or “the list should not be empty.” The mechanism to write these preconditions into code and stop the program immediately with an error if they are not met (if there is a bug) is called “Assertion.” In Python, this is achieved using the assert statement.
This article explains the basic usage of the assert statement, the decisive difference from exception handling (raise), and precautions during operation.
Basic Syntax of the assert Statement
The assert statement evaluates a conditional expression. If it is True, it does nothing and continues processing. If it is False, it raises an AssertionError exception and stops the program.
Syntax:
assert condition, "Error message (optional)"
Specific Example: Verifying Calculation Logic
As an example, let’s create a function that calculates the final payment amount from a product’s list price and a discount amount. In this calculation, we assume that “the payment amount becoming negative” is impossible in terms of logic (a bug that should not exist).
def calculate_payment(price, discount):
"""
Function to calculate payment from price and discount
"""
# Assume there was some complex calculation logic
payment = price - discount
# Assertion: Payment must always be 0 or more
# If negative, there is a bug in the calculation logic or input assumptions
assert payment >= 0, f"Logic Error: Payment is negative ({payment})."
return payment
# --- Execution Test ---
print("Case 1: Normal Calculation")
result = calculate_payment(1000, 300)
print(f"Payment: {result} yen")
print("\nCase 2: Calculation assuming a bug (Discount exceeds price)")
# AssertionError occurs here, notifying the existence of a bug
calculate_payment(1000, 1500)
Output:
Case 1: Normal Calculation
Payment: 700 yen
Case 2: Calculation assuming a bug (Discount exceeds price)
Traceback (most recent call last):
...
AssertionError: Logic Error: Payment is negative (-500).
By inserting the assert statement, the program stops the moment an unexpected state (negative payment) occurs during development, making it easy to identify the cause.
Distinction Between assert and raise (Exception Handling)
A common point of confusion for beginners is “How is this different from checking with an if statement and throwing an exception with raise?”
raise(Exception Handling): Used to handle “errors that can occur during execution,” such as user input mistakes or missing files. These must function even after the product is released.assert(Assertion): Used to check for bugs in the program itself, that is, “things the developer assumes will absolutely never happen.” It is strictly a “debugging tool for developers.”
Disabling via Optimization Option (-O)
The biggest feature of the assert statement is that it is completely ignored (removed) when Python is run in “Optimization Mode (-O option).”
If you run the following in the terminal, assert statements are not executed.
python -O script.py
Therefore, you must never use assert for processing that must always be executed even in a production environment, such as checking user input or validating data.
Bad Example:
def register_user(age):
# Do not use assert to check user input
# If run with python -O, this check disappears, and invalid data gets registered
assert age >= 18, "Minors cannot register"
...
Good Example:
def register_user(age):
# Always use if and raise for mandatory checks
if age < 18:
raise ValueError("Minors cannot register")
...
Summary
- Use
assert condition, messageto check if preconditions are met (if there are no bugs). - If the condition is
False, anAssertionErroroccurs. - It is mainly used for debugging during development and verifying the consistency of internal logic.
- Since it is disabled by Python’s optimization option (
-O), do not use it for mandatory input checks or business logic control; useifstatements andraiseinstead.
