Lesson · Exceptions & Defensive Programming
Assertions & Defensive Programming
55 min readAssertions & Defensive Programming
Assertions document and verify programmer assumptions, not user input. Defensive programming combines validation, invariants, clear failures, and well-defined trust boundaries.
Learning goals
- Sort a check into
assert(the code is wrong) orraise(the input is wrong) and justify the split. - Explain what
python -Odoes to assertions and which checks must survive it. - Read
withdrawand label its first assertion, its twoValueErrorchecks, and its postcondition. - Write an assertion message that names the assumption being tested.
Mental model
The split is about who can fix the failure: an assert that fires means the program itself is wrong, so it is acceptable for the check to disappear under python -O, while validation of user or external input must raise a real exception that optimization cannot remove. Preconditions and invariants describe what each side promises; fail-fast checks are where those promises get verified, close to the operation that depends on them.
Mental model
read it top to bottom
condition that must hold because the code is correct → assert (removed by python -O) input the program does not control → raise ValueError or a custom type state promised across calls → precondition and invariant notice the problem close to its source → fail-fast check
Core idea
Assertions are executable documentation of programmer assumptions, and the moment a check defends against the outside world it must stop being an assert. Defensive programming uses three mechanisms for three trust levels: assert for internal consistency, raise for input the program does not control, and fail-fast checks at the boundaries where the two meet. The cost of getting the split wrong is asymmetric: a stripped assertion lets bad state through, while an assertion used as validation vanishes in optimized execution.
assert
assert is for internal assumptions that indicate a programmer error when false. Optimized execution can remove assertions, so they must not enforce external input validation or security rules.
Intended use
The intended use of assert is to check conditions that must be true if the code is correct, at the point where the code relies on them: a value has the expected shape, a loop maintains its invariant, a helper received what its caller promised. It is not a place to validate user input, file contents, or anything else the program does not control, because python -O removes assertions entirely.
Why assertions are not input validation
Assertions are not input validation because they can be removed at runtime: a program started with the -O flag strips them, so any check written as assert disappears in optimized execution. External input also calls for a response the caller can catch and explain, normally ValueError or a custom type, while an assertion failure signals a bug. Use assert for what should be impossible when the code is right; use raise for what an untrusted source can actually send.
Preconditions
A precondition is a requirement callers must satisfy before an operation. Decide whether violating it is a programming bug, invalid external input, or an ordinary branch, because the reporting mechanism differs.
Invariants
An invariant is a property that must remain true across valid states of an object or algorithm. Protect the whole invariant, especially when multiple fields or concurrent operations participate.
Fail-fast checks
Fail-fast checks reject invalid state close to its source. This shortens the distance between cause and failure and prevents downstream code from operating on corrupted assumptions.
Walkthrough
- The first
assert balance >= 0states the function's precondition in code: if a caller passes a negative balance, the program contradicts itself, and the check fails withinternal invariant failedinstead of computing a nonsense result. amount <= 0andamount > balanceare conditions an external caller can trigger, so they useraise ValueErrorwith the messagesamount must be positiveandinsufficient funds; these checks survivepython -O.new_balance = balance - amountperforms the state change, and the secondassert new_balance >= 0re-checks the invariant afterward: while the earlier checks are correct, this line can never fail.- Predict before running: which check handles
withdraw(100, 150)andwithdraw(100, -5), and whetherwithdraw(-10, 5)fails throughassertorraise.
Experiments to try
- Run
withdraw(100, 25)for the success value, thenwithdraw(-10, 5)under bothpythonandpython -O. Record what changes and connect it to assertion stripping. - Call
withdraw(100, 150)andwithdraw(100, -5). Both raiseValueError, because those checks are validation; confirm they still raise underpython -O. - Replace the first
assertwithif balance < 0: raise ValueError(...)and re-runwithdraw(-10, 5)underpython -O. The failure now survives optimization. - Call
withdraw(100, "25")and note thatamount <= 0raisesTypeErrorbefore any message from this file appears. Addassert isinstance(amount, int)and decide whether that guard should be validation instead.
Common mistakes
- Using
assertto validate external input: the check vanishes underpython -O, so bad data flows into later arithmetic and fails far from its source as aTypeErroror a wrong result. - Relying on
assertfor security or policy: assertions are removable runtime checks, never a boundary an attacker must pass. - Handling
AssertionErrorto keep going: the assertion marked a broken assumption, and continuing past it runs the code the check was protecting. Fix the bug or turn the case into explicit validation. - Leaving assertions unexplained: a bare
assert xyields anAssertionErrorwith no clue which invariant broke; the message should name the assumption being tested.
Practice: Easy
- Run
withdraw(100, 25)andwithdraw(100, 150). Record which check handled each call, the exception type or return value, and the message. - Run
withdraw(-10, 5)underpythonand underpython -O. Explain the different outcomes with the assertion-stripping rule. - Comment out the
amount > balancecheck and find a call that now trips the secondassert, then restore the check.
Practice: Medium
- Rewrite
withdrawso every check a caller can trigger raisesValueErroror a custom type, and every check that can only fail when the code is wrong stays anassert. List which check went where and why. - Write
average(values)with a precondition (len(values) > 0), a postcondition (the result lies betweenminandmax), and one fail-fast check. Choose the mechanism for each and verify the behavior underpython -O. - Take one
assertfrom your own code and interrogate it: can user input reach it, can configuration reach it, does it guard security, does it survive optimization? Convert it toraiseif any answer points outside the program's own logic.
Practice: Hard
- Design a
BankAccountclass with the invariantbalance >= 0, a documented precondition forwithdraw, and fail-fast checks at method entry. State for each check whether it isassertorraise, and justify the split. - Build a two-run lab: run the same failing calls under
pythonandpython -Oand produce a table of which checks still fired. Use it to name the failure modes that were protected only by assertions. - Connect this lesson to testing (a later module): describe which of the class's invariants should become unit tests with plain
assert, and why tests can rely onassertwhile runtime code cannot.
Lesson checklist
- I can sort a check into
assert(the code is wrong) orraise(the input is wrong) and justify the split. - I can explain what
python -Odoes to assertions and which checks must survive it. - I can read
withdrawand label its precondition, its twoValueErrorchecks, and its postcondition. - I can write an assertion message that names the assumption that failed.
Remember
Assertions are executable notes to the next programmer: they say which conditions the code believes are true, and they fire only when the code is wrong, which is why `python -O` is allowed to remove them. Everything the program does not control needs explicit validation with `raise`, and every invariant is worth protecting at the edges where state changes. The split is the lesson: `assert` for assumptions, `raise` for the outside world.
Interview angles
What is the main purpose of **assert**?+
assert is for internal assumptions that indicate a programmer error when false. Optimized execution can remove assertions, so they must not enforce external input validation or security rules.
What should you pay attention to when using **Intended use**?+
The intended use is checking conditions that must be true when the code is correct, at the point the code relies on them. It is not for validating user input or external data, because python -O removes assertions entirely.
How does **Why assertions are not input validation** fit into this lesson?+
Assertions can be stripped at runtime: python -O removes them, so a check written as assert disappears in optimized execution. Input from outside the program needs raise with a catchable type, while an assertion failure signals a bug in the code itself.
What happens to `assert` statements under `python -O`, and why does that make `assert` unsuitable for validating user input?+
The -O flag removes assertions, so a check written as assert simply does not run in optimized mode and invalid input can pass through. Validation of anything outside the program must use raise, which optimization cannot remove.