Use assert condition, "optional message" strictly as a development-time sanity check to catch internal programmer bugs and unreachable invariants (AssertionError)—never for validating user input, file/network data, permissions, or business rules, because running Python with the -O (optimize) flag strips every assert statement from compiled bytecode completely.
Basic Example
def calculate_discount_price(price: float, discount_rate: float) -> float:
# ✅ Runtime input validation: ALWAYS use explicit `if ... raise ValueError`
if price < 0:
raise ValueError(f"Price cannot be negative, got {price}")
if not (0.0 <= discount_rate <= 1.0):
raise ValueError(f"Discount rate must be between 0 and 1, got {discount_rate}")
final_price = price * (1.0 - discount_rate)
# ✅ Internal invariant check: Verifies our own algorithm logic during development/testing
assert 0.0 <= final_price <= price, f"Invariant broken: {final_price=} > {price=}"
return final_price
print(calculate_discount_price(100.0, 0.25))
# Output: 75.0
Key Details & Edge Cases
- Assertions are completely disabled when Python runs with
-O/-OOorPYTHONOPTIMIZE=1:- Under
python -O script.py,__debug__becomesFalseand the compiler omitsassertstatements entirely—neither the condition nor any side-effecting function calls inside it (assert save_record()) will execute! - Therefore, never put security checks, authentication guards, input validation, or state-mutating expressions inside an
assert.
- Under
- Critical syntax trap—never wrap the condition and message in parentheses (
assert (cond, "msg")):- Writing
assert (x > 0, "x must be positive")creates a 2-element tuple(False, "x must be positive"). In Python, any non-empty tuple is always truthy (bool((False, "msg")) == True), so the assertion never fails and triggers aSyntaxWarning: assertion is always true, perhaps remove parentheses?! Always omit outer parentheses:assert x > 0, "x must be positive".
- Writing
- Use
assertinpytesttest suites (wherepytestrewrites AST assertions):- In test frameworks like
pytest, plainassert actual == expectedis the idiomatic standard becausepytestintercepts assertions and generates rich structural diffs on failure.
- In test frameworks like
- Exhaustiveness checks with
typing.assert_never()(Python 3.11+):- In
match/if-chains coveringEnumorLiteralunion branches, calltyping.assert_never(value)in the unreachable fallback branch—giving you both static type-checker exhaustiveness verification (mypy/pyright) and a clear runtimeAssertionErrorif an unexpected value slips through.
- In
Comparison of assert vs. Explicit Exceptions & pytest Assertions
| Mechanism | Disabled by python -O? |
Exception Raised | Side Effects Safe? | Best Used When |
|---|---|---|---|---|
assert cond, msg |
Yes (stripped completely) | AssertionError |
No (skipped under -O) |
Catching internal programmer bugs, postconditions, and impossible states during development. |
if not cond: raise ValueError(...) |
No (always enforced) | ValueError / TypeError / PermissionError |
Yes | Validating external inputs, API payloads, CLI arguments, file data, and security checks. |
assert a == b inside pytest |
Only if pytest itself runs under -O |
AssertionError (with rich diff) |
Yes (test-only code) | Writing unit and integration test assertions in pytest. |
typing.assert_never(val) (3.11+) |
No (raises AssertionError at runtime) |
AssertionError |
Yes | Exhaustive pattern matching over Enum or Literal types checked by mypy/pyright. |
You must log in or register to comment.