Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

The Challenge

Python’s assert statement is often misunderstood and misused as a runtime validation or security mechanism. While assert is perfectly valid for debugging and testing, relying on it for production checks, input validation, or security controls introduces hidden risks that can fundamentally change how an application behaves once deployed.

The core problem: assertions are not guaranteed to execute in production.


The Threat

From a security standpoint, assert is unreliable by design:

In short: assert is not a security boundary.


Vulnerable Code Example

The following example demonstrates how relying on assert for runtime validation leads to different—and unsafe—behavior when Python is run with optimizations enabled.

"""
Vulnerable example: using assert for runtime validation.
"""

def divide_numbers(x, y):
    # Intended to prevent division by zero
    assert y != 0, "Invalid divisor"
    return x / y


print("--- Demonstrating danger of assertions ---")

# Works as expected in normal mode
print(divide_numbers(10, 2))

try:
    # When run with `python -O`, the assert line is removed
    # This will raise ZeroDivisionError instead of AssertionError
    print(divide_numbers(10, 0))
except AssertionError as e:
    print(f"Caught AssertionError: {e}")

Run the script twice:

python assert_example.py
python -O assert_example.py

You will observe different execution paths, proving that the safety check is unreliable.

Secure Mitigation

The only safe alternative in production code is explicit validation with proper exceptions.

"""
Secure example: explicit checks with proper exception handling.
"""

def divide_numbers(x, y):
    if not isinstance(y, (int, float)):
        raise TypeError("Divisor must be a number")

    if y == 0:
        raise ValueError("Divisor must not be zero")

    return x / y


print("--- Secure behavior ---")

try:
    print(divide_numbers(10, 0))
except (TypeError, ValueError) as e:
    print(f"Handled error safely: {e}")

Discussion

When assert is appropriate:

When assert is dangerous:

Key takeaways:

If a condition matters for correctness, stability, or security, never rely on assert.

For more information check: