Module 19 · Debugging, Testing and Best Practices — topic 6 of 15
Assertions
Checking assumptions with assert: syntax and messages, internal invariants versus input validation, assertions as quick self-tests, and why python -O disables them.
Learning objectives
- Write assertions with helpful messages
- Distinguish assertions from input validation
- Use assertions for quick checks and tests
Definition
An assert statement checks that a condition is true and raises AssertionError with an optional message if it isn't: assert condition, message. Assertions document and check assumptions a programmer believes must hold.
Introduction
'This list can never be empty here.' If that belief is wrong, you want to know immediately — not three functions later. assert turns beliefs into checks.
Why it matters
Assertions catch bugs close to their cause, document assumptions in code, and are the building block of tests in pytest.
Detailed explanation
assert condition, "message" does nothing if the condition is true and raises AssertionError("message") if it is false.
Use assertions for things that should be impossible if the code is correct: internal invariants, postconditions and assumptions between your own functions.
Don't use assertions to validate user input or external data; use if statements and raise ValueError or similar.
Running Python with -O (optimise) removes assert statements entirely, so code must not depend on them.
Never put side effects inside assertions (assert items.pop() > 0), because they vanish under -O.
A clear message explaining what was expected saves debugging time.
Quick self-tests — a few assert lines after a function — are an easy first step towards real tests.
pytest uses plain assert statements in tests and shows detailed information when they fail.
Syntax
- assert condition, message.
- For internal assumptions, not input validation.
- Removed by python -O.
Code examples
An assumption checked
3.0 AssertionError: average() needs at least one number
An invariant
70 100
More examples
Self-tests, and what -O does
all slugify checks passed 1 AssertionError: maths is broken 0 assertions skipped
Step-by-step explanation
- Two assert lines act as a tiny test suite for slugify.
- Run normally, the failing assertion stops the child program with exit code 1.
- With -O the assertion is removed entirely, so the program continues — which is why assertions must never be the only safety check.
Expected output
Running “Self-tests, and what -O does” prints exactly:
Practical applications
- Checking invariants in data-processing pipelines during development.
- Tests written with pytest.
Best practices
- Use assertions for internal assumptions.
- Write helpful messages.
- Never rely on assertions for validation or side effects.
Common mistakes
Validating input with assert
Avoid
Prefer
Input validation must always run.
assert with parentheses
Avoid
Prefer
A non-empty tuple is always truthy, so the check never fails.
Important notes
- Python warns about the parenthesised-tuple mistake with a SyntaxWarning.
Key takeaways
- assert checks assumptions and raises AssertionError.
- Not for user input; removed by -O.
- Useful for quick self-tests.
Try it yourself
- 1Add assertions checking that a sorting function's output is sorted and has the same length as the input.
- 2Replace an assert used for input validation with proper error handling.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
2 questions test this exact topic. Answers and explanations are revealed after you submit.
- AdvancedWhy shouldn't assert be used to validate user input?
- AdvancedWhat is printed?