Python Errors and Exceptions · Lesson 99 of 149

Python Assertions and Defensive Programming

What you will learn

  • Writing an assert statement, with a message
  • Why assertions are not for checking input
  • assert versus raise
  • Guard clauses, preconditions, postconditions and invariants
  • Habits of defensive programming

1. The assert statement

An assertion states something that must be true at that point. If it is false, Python raises an AssertionError:

def avg(v):
    assert len(v) > 0, "need at least one value"
    return sum(v) / len(v)

print(avg([1, 2]))
avg([])
1.5
AssertionError: need at least one value

The form is assert condition, message. The message is optional but strongly recommended. Without it you only get AssertionError():

try:
    assert 1 + 1 == 3
except AssertionError as e:
    print(repr(e), e.args)
AssertionError() ()

Put the real values in the message, such as f"expected str, got {type(x).__name__}", so the failure explains itself.

Quick check: what happens when the condition of an `assert` is true?

Nothing. The program carries on.

2. Assertions can be switched off

Python can run with the -O (optimize) option, and then all assert statements are ignored. The built-in constant __debug__ is True normally and False under -O. Take this file:

import sys

def f(x):
    assert x > 0, "x must be positive"
    return x

print(f(-1) if len(sys.argv) > 1 else "no")

Run normally, the check fires; with -O it silently disappears:

$ python check.py go
AssertionError: x must be positive

$ python -O check.py go
-1

(Both outputs come from real runs of that file, shown here by their last line.) This single fact decides how to use assert:

Assertions are for catching bugs in your own code. Never use them to check data from outside, or to enforce rules that must always hold.

Input from users, files, networks or other programs must be checked with a normal if and a raise (lesson 14.4), which can never be switched off.

Problem Right tool
the user typed a negative age if age < 0: raise ValueError(...)
a file is missing an exception from open, handled with try
a function's own calculation went wrong, which "cannot happen" assert
a caller passed the wrong type to your public function raise TypeError(...)

A second trap: do not put needed work inside an assert, because it vanishes under -O:

assert items.pop(0) == "start"      # the pop disappears with -O!

Do the work on its own line, then assert on the result.

A third: parentheses make an assertion always true. assert (cond, "message") tests a two-item tuple, which is never empty, so it passes whatever cond is. Python warns about it:

SyntaxWarning: assertion is always true, perhaps remove parentheses?

Write assert cond, "message" with no parentheses around both.

3. What assertions are good for

Use assert for conditions that, if false, mean there is a bug in the program (not that someone gave bad data):

def withdraw(balance, amount):
    if amount > balance:                      # input rule: always check, raise
        raise ValueError("insufficient funds")
    new = balance - amount
    assert new >= 0, "balance went negative: bug in withdraw"
    return new

print(withdraw(100, 30))
70

The raise handles a user mistake. The assert states what the code above it guarantees, and would catch a mistake in withdraw itself.

Assertions also serve as executable comments: they tell the next reader what you assumed.

Pre- and postconditions, invariants

Term Meaning Example
precondition what must be true before a function runs len(v) > 0
postcondition what the function guarantees afterwards the result is sorted
invariant something true all the time (for example in a loop or class) the balance is never negative
def discount(price, pct):
    if not 0 <= pct <= 100:                   # precondition on input: raise
        raise ValueError(f"pct must be 0-100, got {pct}")
    result = price * (1 - pct / 100)
    assert 0 <= result <= price               # postcondition: assert
    return result

def merge(a, b):
    out = sorted(a + b)
    assert len(out) == len(a) + len(b)
    assert all(out[i] <= out[i + 1] for i in range(len(out) - 1))
    return out

print(discount(200, 25))
print(merge([3, 1], [2]))
150.0
[1, 2, 3]

4. Defensive programming

Defensive programming means writing code that stays safe when things go wrong. Habits worth building:

  1. Validate input at the edges (where data enters), with raise and clear messages. Inside, you may trust it.
  2. Use guard clauses: check the bad cases first and leave early, so the main path is not buried in nesting:
def grade(scores):
    if not scores:
        raise ValueError("no valid scores to grade")
    avg = sum(scores) / len(scores)
    return "pass" if avg >= 50 else "fail"
  1. Fail early and loudly. An error at the cause is easier to fix than a strange result much later.
  2. Do not swallow errors (lesson 14.1): no bare except: pass.
  3. Keep functions small, with a clear job (lesson 11.8).
  4. Prefer immutable data (tuples, frozen dataclasses) when values should not change.
  5. Test the edge cases: empty input, one item, huge values, wrong types (lesson 18.2).
  6. Make the safe thing the default, for example None for "no value" instead of 0 (lesson 11.9).

Defensive does not mean checking everything everywhere: too many checks make code noisy. Check where data enters and where a mistake would be costly.

Worked example: parsing and grading scores

Text such as "70, 85, x, 92, 150, " comes from outside, so it is validated with raise and if. Inside, one assertion guards an internal rule (no item may be lost), and another checks that the average makes sense.

def parse_scores(text):
    """Turn '70, 85, x, 92' into good scores and a list of bad items."""
    if not isinstance(text, str):
        raise TypeError("text must be a string")
    good, bad = [], []
    for part in text.split(","):
        part = part.strip()
        try:
            n = int(part)
        except ValueError:
            bad.append(part)
            continue
        if not 0 <= n <= 100:
            bad.append(part)
        else:
            good.append(n)
    assert len(good) + len(bad) == len(text.split(",")), "lost an item"
    return good, bad


def grade(scores):
    if not scores:
        raise ValueError("no valid scores to grade")
    avg = sum(scores) / len(scores)
    assert 0 <= avg <= 100, "average out of range: bug in parse_scores"
    return "pass" if avg >= 50 else "fail"


good, bad = parse_scores("70, 85, x, 92, 150, ")
print(good, bad)
print(grade(good))

for t in ("x, y", 5):
    try:
        print(grade(parse_scores(t)[0]))
    except (TypeError, ValueError) as e:
        print(type(e).__name__ + ":", e)
[70, 85, 92] ['x', '150', '']
pass
ValueError: no valid scores to grade
TypeError: text must be a string
Check Tool Why
text must be a string raise TypeError comes from the caller: must always be checked
bad items collected try / except and if bad data is expected, not a bug
empty list of scores raise ValueError a guard clause for a case callers can cause
nothing lost assert an internal promise; if false, parse_scores has a bug
average in range assert cannot be false if the scores were validated

The scores are made up.

Common mistakes

  • Using assert to validate user input (it disappears under -O).
  • Putting needed work in the assertion (assert f() == 1 where f has side effects).
  • Writing assert (cond, "msg") with parentheses, which always passes.
  • No message, making the failure hard to understand.
  • Using assert instead of raise in a public function whose arguments come from others.
  • Over-checking every value everywhere.
  • Catching AssertionError to hide a bug.

Key takeaways

  • assert condition, "message" raises AssertionError when the condition is false.
  • Assertions vanish under python -O, so use them only for conditions that mean a bug in your own code.
  • Check external input with if and raise (ValueError, TypeError), which always runs.
  • Never rely on side effects inside an assert; never wrap the condition and message in parentheses together.
  • Defensive habits: validate at the edges, use guard clauses, fail early, and do not swallow errors.

Practice

1. What exception does a failed assert raise?

Show answer

AssertionError.

2. Why should assert age >= 0 not be used to check a user's input?

Show answer

Assertions are removed when Python runs with -O, so the check could silently disappear. Use if age < 0: raise ValueError(...).

3. What is wrong with assert (x > 0, "x must be positive")?

Show answer

The parentheses make a two-item tuple, which is always true, so the assertion never fails. Remove the parentheses.

4. Rewrite so it still works under -O: assert queue.pop() == "end".

Show answer
last = queue.pop()
assert last == "end"

The pop now runs even when assertions are off.

5. What is a guard clause?

Show answer

A check at the top of a function that handles a bad or special case early (by raising or returning), so the rest of the function can assume the normal case.

6. Give an example of a postcondition for a sorting function.

Show answer

The result is in order, and it has the same number of items as the input.