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.
4assert selected isnotNone,"Algorithm failed to select candidate."
5return selected
1
Checking "Can Never Happen" Cases:
1defprocess_direction(direction):
2if direction =="NORTH":
3 move_north()
4elif direction =="SOUTH":
5 move_south()
6else:
7# If code reaches here, internal program logic is corrupt
8assertFalse,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:
1# In optimized mode, ALL assertions are completely deleted and ignored!
2python -O app.py
Consider this critical security flaw:
1# DANGEROUS SECURITY FLAW:
2defdelete_user_account(user, target_id):
3assert user.is_admin,"Admin permissions required!"# Stripped when running python -O!
4 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!
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!
1# FATAL TRAP: Parenthesizing the condition and message
2assert(1==2,"This condition is obviously false!")
3# This assertion NEVER fails! Python evaluates the non-empty tuple as True!
4
5# CORRECT:
6assert1==2,"This condition is obviously false!"
7# Correctly raises AssertionError
⚠️ Common Intermediate Mistakes & Gotchas
1. Using assert for Production Input Validation
Python disables all assertions when run with optimization flags (python -O script.py). Never rely on assertions for business logic, authentication, or input validation. Use if ...: raise ValueError(...) instead.
2. Passing a Tuple to assert
assert(condition, "error message") evaluates a non-empty 2-element tuple, which is ALWAYS truthy in Python! Write assert condition, "error message" without outer parentheses.
💻 Try It Yourself: Invariant Assertion Checker
Scenario
Write a function distribute_shares(total_shares, num_partners) using assertions to guarantee that total shares remain conserved without creating fractional phantom shares.