assert — Advanced Examples
Debugging aid that tests a condition and raises AssertionError if false
Assert pitfalls
Common mistakes with assert statements.
python
# PITFALL 1: assert with a tuple is always True! # assert(condition, "message") <-- WRONG! This is assert (tuple,) # assert condition, "message" <-- RIGHT try: x = -1 assert x > 0, "Must be positive" except AssertionError as e: print(f"Caught: {e}") # Tuple form is always truthy (non-empty tuple) value = (False, "this is always truthy") print(f"Tuple truthiness: {bool(value)}") # PITFALL 2: assert is a statement, not a function # These are different: # assert(False, "msg") -> asserts a non-empty tuple (always True!) # assert False, "msg" -> asserts False with message "msg" # Demonstrate the difference try: assert False, "correct usage" except AssertionError as e: print(f"Correct: {e}")
The most common assert pitfall is writing assert(cond, msg) with parentheses — this creates a non-empty tuple which is always truthy. Use assert cond, msg without parens.
Want to try these examples interactively?
Open Advanced Playground