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 / -OO or PYTHONOPTIMIZE=1:
    • Under python -O script.py, __debug__ becomes False and the compiler omits assert statements 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.
  • 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 a SyntaxWarning: assertion is always true, perhaps remove parentheses?! Always omit outer parentheses: assert x > 0, "x must be positive".
  • Use assert in pytest test suites (where pytest rewrites AST assertions):
    • In test frameworks like pytest, plain assert actual == expected is the idiomatic standard because pytest intercepts assertions and generates rich structural diffs on failure.
  • Exhaustiveness checks with typing.assert_never() (Python 3.11+):
    • In match / if-elif chains covering Enum or Literal union branches, call typing.assert_never(value) in the unreachable fallback branch—giving you both static type-checker exhaustiveness verification (mypy/pyright) and a clear runtime AssertionError if an unexpected value slips through.

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.