Skip to contentSkip to navigation

Module 16 · Lesson 03

Assertions and Defensive Programming

State your code's assumptions with assert, validate outside input with real exceptions, fail fast with guard clauses, protect shared data with defensive copies, and know why asserts must never guard user input.

  • About 10 minutes
  • Builds on earlier lessons
  • 12-question quiz at the end

What you will learn

  • assert your assumptions
  • Validate input with real exceptions
  • Guard clauses first
  • Watch the guards at work

Catch mistakes early

Defensive code checks its assumptions and refuses bad data before it can do damage.

  • assert

    assert total >= 0, "negative total" stops the program if your own logic is wrong.

  • Real exceptions

    Check outside input with if and raise ValueError. Those checks always run.

  • Guard clauses

    Handle the bad cases first and return early, so the main path stays flat.

  • Defensive copies

    Copy a list you were given before keeping it, so outside changes cannot reach in.

Defensive code everywhere

Systems that must not fail check everything at the door.

  • BankingA transfer refuses a negative amount before any money moves.
  • Sign-up formsReject an empty email address before saving anything.
  • SensorsCheck that every reading is in a sensible range before acting on it.
  • Testsassert add(2, 2) == 4 is how many test tools check results.

Reading an assert

This line states something that must be true if the code is correct. Tap each part to see its job.

Part 1 of 4

Tap any part of the code below, or press Next.1 of 4 explored

assert:Checks a condition. If it is False, Python raises AssertionError.

Check before you trust

Pick an example, change it, then press Run. Say what you expect to see before you press.

Example 1 of 6assert in action

The assert states what average needs. It stays silent while that holds.

Your turn: Call average([]) on a new line and read the message.

Python
def average(nums):
    assert len(nums) > 0, "average needs at least one number"
    return sum(nums) / len(nums)

print(average([4, 8, 6]))
print(average([10]))
Output
Press Run to see what it prints.

Watch the guards at work

Press Step to run one line at a time. Watch the names box change.

Ready. Press Step to run the first line.

  1. def withdraw(balance, amount):
  2. if amount <= 0:
  3. raise ValueError("amount must be positive")
  4. if amount > balance:
  5. return balance, "refused"
  6. new = balance - amount
  7. assert new >= 0
  8. return new, "ok"
  9. print(withdraw(50, 20))
  10. print(withdraw(50, 80))

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.A copy of a list of lists:

a = [[1], [2]]
b = list(a)
b[0].append(9)
print(a)

0 of 6 answered

Common defensive coding misconceptions

Each card is something learners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

The assert statement

assert checks that a condition is true. If it is, nothing happens. If it is false, Python raises AssertionError, with an optional message:

Try it 1: edit me, then Run
def average(scores):
    assert len(scores) > 0, "average() needs at least one score"
    return sum(scores) / len(scores)

average([])   # AssertionError: average() needs at least one score
Output
Press Run to see what it prints.

Read assert condition, message as "I am certain this is true here; if it is not, there is a bug". The message is shown in the error, so make it say what was expected.

What asserts are for

An assertion documents and checks an assumption about your own code: something that can only be false if a programmer made a mistake. Typical places:

  • Preconditions: what must be true when a function starts, for arguments that come from other parts of your program.
  • Postconditions: what must be true of the result before returning, such as "the list is now sorted".
  • Invariants: facts that must always hold for an object, such as "the balance equals the sum of the transactions".

They make assumptions visible to readers and catch bugs close to where they happen.

What asserts are not for

Assertions can be switched off. Running Python with the -O (optimise) flag removes every assert statement from the program. That makes them wrong for anything that must always be checked:

  • Never validate user input, file contents, network data or function arguments from outside code with assert.
  • Never put actions with side effects inside an assert, such as assert save(record), because with -O the save disappears too.

For problems the program must handle, raise a real exception that names the problem:

Try it 2: edit me, then Run
def set_age(age):
    if not isinstance(age, int):
        raise TypeError(f"age must be an int, got {type(age).__name__}")
    if age < 0:
        raise ValueError(f"age cannot be negative, got {age}")
    return age
Output
Press Run to see what it prints.

A simple rule: bad input raises an exception; a broken assumption in your own code fails an assert.

Fail fast

The defensive idea behind both is fail fast: stop at the first sign of trouble, as close to the cause as possible. Compare two versions of the same bug. In one, a negative quantity is accepted, stored, added into a report and finally shows up as a strange total in a spreadsheet next month. In the other, the line raise ValueError("quantity must be positive, got -3") stops the program the moment the bad value arrives, with the value in the message. The second is far cheaper to fix.

Failing fast also means not hiding errors. A bare except: pass that swallows every exception turns a loud, findable bug into silent wrong behaviour. Catch only the exceptions you can genuinely handle, and let the rest propagate.

Guard clauses

Checks are easiest to read at the top of a function, each one leaving early. These are guard clauses:

Try it 3: edit me, then Run
def ship(order):
    if not order["paid"]:
        return "waiting for payment"
    if not order["items"]:
        return "nothing to ship"
    if order["country"] not in SHIPPING:
        raise ValueError(f"cannot ship to {order['country']}")
    return f"shipping {len(order['items'])} items"
Output
Press Run to see what it prints.

Compare that with the same logic as nested if statements four levels deep, with the real work buried at the bottom and the error cases scattered in else branches far from their conditions. Guards keep the main path flat and put each rule next to its consequence.

Ask forgiveness or look before you leap

Python programmers often prefer EAFP, "easier to ask forgiveness than permission": try the operation and catch the specific exception, rather than checking everything first (LBYL, "look before you leap"):

Try it 4: edit me, then Run
try:
    price = prices[item]
except KeyError:
    raise ValueError(f"unknown item {item!r}") from None
Output
Press Run to see what it prints.

EAFP avoids checks that go out of date (a file can be deleted between checking it exists and opening it) and avoids doing the same lookup twice. LBYL is clearer for simple value rules like "must be positive". Both are defensive; the point is to choose deliberately and produce a clear error.

Defensive copies

Mutable arguments are shared with the caller. A function that sorts or changes a list it was given changes the caller's list too, which surprises them. The defensive habit is to copy when you need to change something you were given, items = list(items) or sorted(items), and to return copies (or tuples) of internal lists instead of the lists themselves, so outside code cannot break an object's invariants behind its back.

Asserts in tests

The same assert keyword is the backbone of automated tests: test tools such as pytest run functions full of asserts like assert total([2, 3]) == 5. There, checking that your code does what you expect is exactly the point, and tests are never run with -O.

Syntax

The general shape of the statements in this lesson.

syntax.py
assert condition                     # AssertionError if False
assert condition, "message"          # with a message
python -O script.py                  # removes all asserts!

if value < 0:                        # validate input: always runs
    raise ValueError(f"... {value}")
if not isinstance(x, int):
    raise TypeError("x must be an int")

def f(x):                            # guard clauses
    if bad1:
        return ...                   # or raise
    if bad2:
        raise ValueError(...)
    return main_work(x)

items = list(items)                  # defensive copy before changing
return tuple(self._items)            # hand out a read-only view
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

A discount function with guard clauses

Beginner

Write discounted(price, percent) that rejects wrong types and impossible values with clear exceptions, then asserts its own result is sensible before returning it.

Python
def discounted(price, percent):
    if not isinstance(price, (int, float)) or isinstance(price, bool):
        raise TypeError(f"price must be a number, got {type(price).__name__}")
    if price < 0:
        raise ValueError(f"price cannot be negative, got {price}")
    if not 0 <= percent <= 100:
        raise ValueError(f"percent must be 0 to 100, got {percent}")
    result = round(price * (100 - percent) / 100, 2)
    assert 0 <= result <= price, "a discount can never raise the price"
    return result

print(discounted(80, 25))
print(discounted(19.99, 0))
for bad in [("80", 10), (-5, 10), (50, 120)]:
    try:
        discounted(*bad)
    except (TypeError, ValueError) as error:
        print(type(error).__name__ + ":", error)
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

The guards come first and each raises an exception naming the bad value, because these are problems with input from callers. The assert at the end checks the function's own arithmetic: if it ever failed, the bug would be in this code, not in the arguments. bool is excluded because True and False are technically ints.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Validating user input with assert

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
def withdraw(balance, amount):
    assert amount > 0, 'amount must be positive'
    return balance - amount

# run with: python -O bank.py
print(withdraw(100, -50))
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

With -O the assert is removed and the result is 150: a negative withdrawal adds money

Write this instead

def withdraw(balance, amount):
    if amount <= 0:
        raise ValueError('amount must be positive')
    return balance - amount

Why it happens

Asserts can be switched off, so they must never be the only protection against bad input.

In the real world

Where this shows up in software people use every day.

  1. Reserving warehouse stock safely

    Logistics

    A warehouse system reserves stock for incoming orders from several shop websites. Orders are outside data and are checked with exceptions. The stock table is internal, so its invariant (no item ever goes below zero) is asserted. Orders are checked completely before any stock changes, so a bad line never leaves an order half reserved.

    Why Python fits

    All checks run before the first change, so the second order, which fails on its lamp line, leaves the mugs untouched too. Each rejection names the exact problem. The assert at the end is not input validation: it can only fail if the reserving code itself is wrong, which is precisely what an assertion is for.

    Python
    class OrderError(Exception):
        pass
    
    stock = {"mug": 10, "lamp": 2, "rug": 0}
    
    def reserve(order_lines):
        lines = [(item, qty) for item, qty in order_lines]   # defensive copy
        if not lines:
            raise OrderError("order has no lines")
        for item, qty in lines:
            if item not in stock:
                raise OrderError(f"unknown item {item!r}")
            if not isinstance(qty, int) or qty <= 0:
                raise OrderError(f"bad quantity {qty!r} for {item}")
            if qty > stock[item]:
                raise OrderError(f"only {stock[item]} {item} left")
        for item, qty in lines:
            stock[item] -= qty
        assert all(count >= 0 for count in stock.values()), "stock went negative"
        return f"reserved {sum(qty for _, qty in lines)} items"
    
    orders = [
        [("mug", 3), ("lamp", 1)],
        [("mug", 2), ("lamp", 5)],
        [("vase", 1)],
        [("mug", "2")],
        [],
    ]
    for order in orders:
        try:
            print(reserve(order))
        except OrderError as error:
            print("rejected:", error)
    print("stock now:", stock)
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

How many asserts should I write?

Enough to state the assumptions a reader might not see and that would cause confusing failures later. Asserting the obvious on every line adds noise; asserting a tricky invariant after a complex update is valuable.

Does anyone really run Python with -O?

Some deployment setups do, often without the programmers realising. That is exactly why asserts must never be the only check on something important.

Should I check every argument's type?

No. Check types and values at the boundaries where data enters your program: user input, files, network requests and public functions of a library. Inside your own code, type annotations and a type checker are usually a better way to catch type mistakes.

Is raising an exception better than returning None for bad input?

Usually. None is easy to ignore and tends to cause an unrelated error later. An exception stops at the cause with a message, and a caller who can handle it can still catch it.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/3 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 15 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.