assertIntermediate Examples

Debugging aid that tests a condition and raises AssertionError if false

Assert in testing and debugging

Using assert for preconditions, postconditions, and invariants.

python
# Precondition
def binary_search(arr, target):
    assert arr == sorted(arr), "Array must be sorted"
    lo, hi = 0, len(arr) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

print(binary_search([1, 3, 5, 7, 9], 5))

# Postcondition
def factorial(n):
    result = 1
    for i in range(2, n + 1):
        result *= i
    assert result > 0, "Factorial must be positive"
    return result

print(factorial(10))

# Type checking assertions
def concat(a, b):
    assert isinstance(a, str) and isinstance(b, str), \
        f"Expected strings, got {type(a).__name__} and {type(b).__name__}"
    return a + b

print(concat("hello", " world"))
Expected Output
2
3628800
hello world

assert is ideal for checking invariants during development. Use it for conditions that should never be false in correct code.

Assert vs raising exceptions

When to use assert vs explicit exceptions.

python
# BAD: assert for user input (disabled with -O)
# assert username != "", "Username required"

# GOOD: raise for user input validation
def create_user(username):
    if not username:
        raise ValueError("Username required")
    return {"name": username}

# GOOD: assert for internal invariants
def _process_internal(data):
    assert isinstance(data, list), "Bug: expected list"
    assert len(data) > 0, "Bug: empty data"
    return sum(data) / len(data)

print(create_user("alice"))
print(_process_internal([1, 2, 3]))

try:
    create_user("")
except ValueError as e:
    print(f"Proper error: {e}")
Expected Output
{'name': 'alice'}
2.0
Proper error: Username required

Use assert for internal invariants only. Use raise for input validation, because assert can be disabled with python -O.

Want to try these examples interactively?

Open Intermediate Playground