Exception Handling with try and except
The assert statement verifies that a condition is true; if false, it raises an AssertionError
A Check Before the Next Step
Imagine that a program is about to use the first item in a list. The programmer expects the list to contain at least one item. An assert statement lets the program verify that assumption immediately. If the assumption is true, execution continues. If it is false, Python stops at the assertion and raises an AssertionError.
How assert Verifies an Assumption
The assert statement verifies that a condition is true. Its first part is the keyword assert, followed by a condition, which can be any boolean expression. If the condition is true, the assertion passes silently and execution continues. If the condition is false, Python immediately raises an AssertionError.
In this example, the list has one element, so len(items) >= 1 is true. The assertion produces no output of its own, and the print statement can execute. A passing assertion is therefore silent: its effect is that execution is allowed to continue.
The list contains an item.Locating the Failure
What do you think happens?
What happens when the list is empty and execution reaches the assertion?
Reveal answer
Answer: The assertion raises an AssertionError.
An empty list makes len(items) >= 1 false. Python immediately raises an AssertionError, so execution halts at that assertion rather than reaching the next statement.
AssertionErrorThe important location is the assert statement itself. Python evaluates the condition, finds it false, raises AssertionError, and stops there. The later print statement does not execute. Python also displays a traceback identifying the line that caused the problem, which helps pinpoint where the program's assumption was violated.
Messages and Exception Handling
A custom message can be added after a comma. The message is displayed when the assertion fails, making the AssertionError more informative. It should explain which assumption mattered and what went wrong.
AssertionError: items must contain at least one elementPractical Boundaries
Use an assertion when you want to verify an assumption during development or debugging, such as the expectation that a list contains at least one element. Include a descriptive message when the reason for the check may not be obvious. Do not make production-critical logic depend on an assertion: Python's -O flag can disable assertions.
Treating a passing assertion as output.
A passing assertion completes silently.
Fix:
Remember that a true assertion simply allows execution to continue.Ignoring the statement after a failed assertion.
A failed assertion raises AssertionError and halts execution at that point.
Fix:
Trace the program from the failed assert; later statements are not reached.Using assertions for expected runtime errors.
Assertions are a development and debugging tool, not a replacement for proper exception handling.
Fix:
Use appropriate exception handling for expected runtime errors.Relying on assertions for production-critical logic.
Assertions can be disabled with Python's -O flag.
Fix:
Keep production-critical checks independent of assertions.
Check Your Understanding
Consider this sequence: a list is created empty, an assertion checks that its length is at least 1, and a print statement follows. Identify the condition's value, the exception produced, and whether the print statement executes. Then add a custom message that explains the violated assumption.
Hints
- Evaluate len(items) >= 1 for an empty list.
- A false assertion raises AssertionError.
- Execution stops at the failed assertion, so inspect the order of the statements.
Tracing an Empty List
Determine what happens when an empty list is checked with assert len(items) >= 1.
Evaluate the condition: The list has no elements, so the condition len(items) >= 1 is false.
Raise the exception: Because the condition is false, Python raises an AssertionError immediately.
Check the next line: Execution halts at the assertion, so a statement after it is not reached.
Improve the diagnostic: Adding a comma and a message string makes the failure explain which assumption was violated.
The assertion fails at its own line, raises AssertionError, and prevents later statements from executing.
Key Takeaways
- assert verifies that a boolean condition is true.
- A true assertion passes silently and execution continues.
- A false assertion immediately raises AssertionError and identifies the failure location through the traceback.
- A comma followed by a message string makes a failed assertion more informative.
- Assertions support development and debugging, but they should not handle expected runtime errors or enforce production-critical logic because Python's -O flag can disable them.