Assertions0%

Assertions

Beginner12 min readUpdated: Jul 11, 2026
Study Materials

Assertions in Python

An Assertion is a debugging sanity check that tests if a condition is True. If the condition evaluates to False, Python immediately halts execution and raises an AssertionError. Assertions are designed for developers to detect impossible internal states and logic bugs during development, not as everyday control-flow or user input validation mechanisms.


1. The assert Statement Syntax

The syntax for an assertion is straightforward:

Python
assert condition, "Optional descriptive error message"

Under the hood, Python translates this directly into:

Python
if __debug__:
if not condition:
raise AssertionError("Optional descriptive error message")

Basic Example

Python
def calculate_average(scores):
# Sanity check: Function requires non-empty sequence
assert len(scores) > 0, "Scores list cannot be empty."
return sum(scores) / len(scores)
 
print(calculate_average([80, 90, 100])) # 90.0
 
try:
calculate_average([]) # Triggers AssertionError
except AssertionError as err:
print(f"Assertion caught: {err}")

2. When to Use Assertions

Assertions should be used to verify internal invariants—conditions that must always be true unless there is a bug in the code:

  1. 1
    Internal Function Invariants:
Python
def apply_tax(subtotal, tax_rate):
assert 0.0 <= tax_rate <= 1.0, f"Tax rate must be between 0 and 1, got {tax_rate}"
return subtotal * (1 + tax_rate)
  1. 1
    Post-condition Verification:
Python
def retrieve_top_candidate(candidates):
# Algorithm to select candidate...
selected = max(candidates, key=lambda c: c["score"])
assert selected is not None, "Algorithm failed to select candidate."
return selected
  1. 1
    Checking "Can Never Happen" Cases:
Python
def process_direction(direction):
if direction == "NORTH":
move_north()
elif direction == "SOUTH":
move_south()
else:
# If code reaches here, internal program logic is corrupt
assert False, f"Unhandled direction state: {direction}"

3. The Dangerous Trap: When NOT to Use Assertions

Never use assertions for:

  • User input validation (validating forms, API request payloads, or command line arguments).
  • Authentication or security checks (e.g. checking if a user is an admin).
  • Data integrity operations with side effects (e.g. assert f.close()).

Why? The Optimization Flag (-O) Disables Assertions!

When Python is run with the -O (optimize) or -OO flag, the interpreter sets the internal __debug__ flag to False and completely strips all assert statements from the generated bytecode:

Bash / Terminal
# In optimized mode, ALL assertions are completely deleted and ignored!
python -O app.py

Consider this critical security flaw:

Python
# DANGEROUS SECURITY FLAW:
def delete_user_account(user, target_id):
assert user.is_admin, "Admin permissions required!" # Stripped when running python -O!
database.delete(target_id)

If this script is run with python -O, the assert statement is skipped entirely, allowing any standard user to delete accounts!

The Solution: Use Real Exceptions for Validation

Python
# SECURE AND SAFE:
def delete_user_account(user, target_id):
if not user.is_admin:
raise PermissionError("Admin permissions required!")
database.delete(target_id)

4. Syntax Trap: Parentheses in Assertions

In Python, non-empty tuples evaluate to True. Putting parentheses around an assertion and its message creates a 2-element tuple, which always passes, even when the condition is false!

Python
# FATAL TRAP: Parenthesizing the condition and message
assert (1 == 2, "This condition is obviously false!")
# This assertion NEVER fails! Python evaluates the non-empty tuple as True!
 
# CORRECT:
assert 1 == 2, "This condition is obviously false!"
# Correctly raises AssertionError

Multiple Choice Questions

1. Which exception is raised when an assert statement fails?

A. ValueError B. AssertionError C. SystemError D. ConditionError Answer: B Explanation: If an assertion's boolean condition evaluates to False, Python immediately raises an AssertionError.


2. What happens to assertions when running a Python script with the -O (optimize) command-line flag?

A. Assertions are converted to print statements B. All assertions are completely removed and ignored by the bytecode compiler C. Assertions run twice as fast D. Assertions raise Warning instead of AssertionError Answer: B Explanation: Running python -O disables the __debug__ flag and compiles bytecode with all assert statements completely omitted.


3. Why is it dangerous to use assert for validating user inputs in production?

A. Assertions cannot check string lengths B. Assertions can be bypassed completely when running in optimized mode (-O), leaving inputs unvalidated C. Assertions only work in the interactive shell D. Assertions consume too much network bandwidth Answer: B Explanation: Because assertions are stripped in optimized mode (python -O), relying on them for input or security validation introduces major vulnerabilities. Use explicit if / raise ValueError instead.


4. What is the bug in writing assert (x > 0, "x must be positive")?

A. Python raises a SyntaxError on parentheses B. The comma creates a non-empty tuple, which evaluates to truthy, so the assertion never fails C. It only tests negative numbers D. x is converted to a string Answer: B Explanation: In Python, assert (a, b) treats (a, b) as a tuple. A non-empty tuple is always truthy, so the assertion will never raise an error.


5. What is the primary intended purpose of assertions in Python software engineering?

A. Replacing try-except blocks B. Internal sanity checks for developers to verify impossible conditions during development C. Printing text to the command line D. Allocating memory for data structures Answer: B Explanation: Assertions serve as internal consistency checks during development to confirm assumptions about program state.


Next Lesson

Project: Debugging a Student Grading App

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

PrevNext