Defensive Programming Practices
The assert statement verifies that a condition is true; if false, it raises an AssertionError
A Check Before the Next Step
Defensive programming means checking important assumptions before the program relies on them. In Python, the assert statement is a development and debugging tool for this purpose. It verifies that a condition is true. If the condition is true, execution continues silently. If the condition is false, Python raises an AssertionError immediately.
Imagine that later code assumes a list contains at least one item. An assertion can verify that assumption at the point where it matters. This helps reveal the exact place where the program state stopped matching the developer's expectation.
Tracing a List Assumption
Verifying that a list is nonempty
A program expects a list to contain at least one element. Verify that assumption before the program continues.
Create the state: The list contains one element, so its length is at least 1.
Evaluate the condition: The assertion checks whether the list length is at least 1. The condition is true.
Continue execution: Because the condition is true, the assertion passes silently and the next statement can run.
The assertion produces no output or error when the list has one element.
The assumption holdsThe important point is not that assert prints a confirmation. A passing assertion is silent. Its job is to stop execution only when the checked assumption is false.
Assertion Failure in Execution
When Python encounters assert, it first evaluates the condition. A false condition causes Python to raise an AssertionError immediately. The program halts at that point, so statements after the failed assertion do not run. The traceback identifies the line containing the failed assertion, pinpointing where the assumption was violated.
AssertionErrorMaking Failures Informative
An assert statement has a required keyword and condition. The condition can be any boolean expression. You can optionally add a comma followed by a message string. When the assertion fails, Python includes that message in the AssertionError output, making the violated assumption easier to understand.
Practical Boundaries
Assertions are intended for development and debugging. They help catch logic errors and verify assumptions about program state. They are not a replacement for proper exception handling when the program must handle expected runtime errors.
Using an assertion as the main handling mechanism for an expected runtime error
Assertions are development and debugging tools, not substitutes for proper exception handling in production code.
Fix:
Use assertions to verify assumptions and use appropriate exception handling for expected runtime errors.Relying on an assertion for production-critical logic
Assertions can be disabled with Python's -O flag.
Fix:
Keep critical production logic independent of assertions.Leaving a failed assertion without useful context
The failure identifies an AssertionError, but it does not explain why the assumption mattered.
Fix:
Add a descriptive message after a comma when extra context would help debugging.Expecting a passing assertion to display confirmation
A true assertion passes silently.
Fix:
Treat the absence of output or error as the normal result of a passing assertion.
Check Your Reasoning
A program expects a list to contain at least one element. Write an assertion that checks this assumption and includes a message explaining the failure. Then state what happens to the next statement when the list is empty.
Hints
- Use the list length as the condition.
- Place a comma and a descriptive message after the condition.
- A false condition raises AssertionError and stops execution at the assertion.
What do you think happens?
Suppose the list is empty and the assertion checks whether its length is at least 1. What happens to the statement immediately after the assertion?
Reveal answer
Answer: It does not run because an AssertionError is raised.
Python evaluates the condition, raises AssertionError when the condition is false, and halts execution at that point.
Key Takeaways
- assert verifies that a boolean condition is true.
- A true assertion passes silently and execution continues.
- A false assertion raises AssertionError immediately and stops execution at that line.
- A comma followed by a message makes a failed assertion more informative.
- Use assertions for development and debugging, not for production-critical logic or expected runtime error handling.
Key Takeaways
- Use assert to verify assumptions about program state during development and debugging.
- Python evaluates the assertion condition before continuing.
- A false condition raises AssertionError and prevents later statements from running.
- Add a descriptive message after a comma to clarify the violated assumption.
- Do not rely on assertions for production-critical checks because Python can disable them with the -O flag.