Using Assertions in Python

Learn how to use assertions for error handling purposes in Python.

Assertions are to be used for situations that should never happen, so the expression on the assert statement has to mean an impossible condition. Should this condition happen, it means there is a defect in the software.

When assertions are used

In contrast to the error handling approach, there are situations in which we don't want our program to continue its execution if a particular error occurs. This is because, in some cases, the error cannot be overcome and our program cannot correct its course of execution (or self-heal). So it's better to fail fast and let the error be noticed, so it can be corrected in the next version upgrade.

The idea of using assertions is to prevent the program from causing further damage if such an invalid scenario is presented. Sometimes, it is better to stop and let the program crash rather than let it continue processing under the wrong assumptions.

Implementing assertions

By definition, an assertion is a Boolean condition in the code that must hold true for the program to be correct. If the program fails because of an AssertionError, it means a defect has just been uncovered.

For this reason, assertions should not be mixed with the business logic, or used as control flow mechanisms for the software. The following example is a bad idea:

Get hands-on with 1200+ tech skills courses.