Skip to content

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.

Beginner 8 min read·Lesson 284 of 306 in Python Programming

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

Python
def average(nums):
assert len(nums) > 0, "average() needs at least one number"
return sum(nums) / len(nums)
assert average([2, 4]) == 3
  • assert condition, message.
  • For internal assumptions, not input validation.
  • Removed by python -O.

Code examples

An assumption checked

Python
def average(nums):
assert len(nums) > 0, "average() needs at least one number"
return sum(nums) / len(nums)
print(average([2, 4]))
try:
average([])
except AssertionError as e:
print("AssertionError:", e)
Output
3.0
AssertionError: average() needs at least one number

An invariant

Python
def withdraw(balance, amount):
new_balance = balance - amount if amount <= balance else balance
assert new_balance >= 0, f"balance went negative: {new_balance}"
return new_balance
print(withdraw(100, 30), withdraw(100, 300))
Output
70 100

More examples

Self-tests, and what -O does

Python
import subprocess
import sys
def slugify(text):
return "-".join(text.lower().split())
assert slugify("Hello World") == "hello-world"
assert slugify(" A B ") == "a-b"
print("all slugify checks passed")
code = "assert 1 + 1 == 3, 'maths is broken'\nprint('assertions skipped')"
normal = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True)
optimised = subprocess.run([sys.executable, "-O", "-c", code], capture_output=True, text=True)
print(normal.returncode, normal.stderr.strip().splitlines()[-1])
print(optimised.returncode, optimised.stdout.strip())
Output
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:

TextOutput
all slugify checks passed
1 AssertionError: maths is broken
0 assertions skipped

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

assert age >= 0, "invalid age" # disappears with -O

Prefer

if age < 0:
raise ValueError("age must be non-negative")

Input validation must always run.

assert with parentheses

Avoid

assert (x > 0, "x must be positive") # always true

Prefer

assert x > 0, "x must be positive"

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

  1. 1
    Add assertions checking that a sorting function's output is sorted and has the same length as the input.
  2. 2
    Replace 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?
Practise this topic