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
assertstatements, both with and without an explanatory message, and state precisely what happens when the asserted condition isFalse; - distinguish when an
assertis the right tool (checking a function's own assumptions about its parameters, or an internal invariant) from when araised 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
assertandraise; - 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
- The
assertstatement - When to
assert, when toraise - Closing Stage 5
Before you start
The full lesson, with worked examples and exercise solutions, is for members.
Read the full lessonNew to SelfMadeQuant.com? See membership options or browse the Python for Quantitative Finance syllabus.