Definition
A “sanity check” used during development to ensure that the code is not doing something obviously wrong. An assertion is a condition that must be true for the program to be correct.
Why It Matters
They act as an early-warning system that stops bugs from silently corrupting data and causing massive, untraceable failures. Using them ensures that code fails loudly and early at the exact moment a rule is violated.
Core Concepts
assertStatement:assert condition, 'Error message if condition is False'.- Fail-Fast: If the condition is false, Python immediately raises an
AssertionError. - Intended Audience: Assertions are for Programmer Errors, not user errors. They mark states that “should never happen.”
- Disabling: Assertions can be disabled by running Python with the
-O(optimize) flag. For this reason, never use assertions for critical logic (like data validation).
door_status = 'open'
assert door_status == 'open', 'The door must be open to proceed.'
door_status = 'closed'
# This will raise an AssertionError:
assert door_status == 'open', 'The door must be open to proceed.'