Skip to content
Python for Quantitative Finance / Files, Exceptions, and Modules

Assertions and Defensive Programming

Exceptions and Control Flow showed how to handle exceptions gracefully once they occur. This short closing note of Stage 5 covers the opposite habit: proactively checking, at the point a possible violation would occur, that a computation's state actually is what the code assumes it to be — and failing loudly, immediately, if it is not. The assert statement is Python's lightweight tool for exactly this. Confirming an assumption the moment it might be violated, rather than letting a silently-wrong value propagate for dozens of lines before it eventually causes a confusing failure somewhere else, is the single habit this note asks readers to adopt as a default.
Learning objectives. By the end of this note you should be able to:
  • write assert statements, both with and without an explanatory message, and state precisely what happens when the asserted condition is False;
  • distinguish when an assert is the right tool (checking a function's own assumptions about its parameters, or an internal invariant) from when a raised exception is more appropriate (a condition a well-behaved caller could legitimately trigger and should be expected to handle);
  • explain the "overt bugs are better than covert bugs" principle and connect it to both assert and raise;
  • close Stage 5 by restating the module/file/exception discipline this topic has built, as preparation for Stage 6's object-oriented programming.

In this lesson

  1. The assert statement
  2. When to assert, when to raise
  3. Closing Stage 5

Before you start

The full lesson, with worked examples and exercise solutions, is for members.

Read the full lesson

New to SelfMadeQuant.com? See membership options or browse the Python for Quantitative Finance syllabus.