Invariant checking
Check an internal invariant after transforming data.
Python · Const
assert performs a debugging check and raises AssertionError when its condition is false. An optional expression supplies the failure value, but optimized execution can disable assertions.
An assert statement evaluates a condition only when debugging is enabled. If the condition is false, Python raises AssertionError; the optional expression supplies the exception's value. Because assertions can be disabled with optimized execution, use them for internal debugging checks rather than required runtime validation.
assert expression ["," expression]| Name | Type | Description |
|---|---|---|
expression / expression1 | expression | Boolean-like condition to test; the assertion fails when it evaluates as false. |
expression2 | expression | Optional value used to construct AssertionError when the condition fails. |
__debug__ flag.def average(total, count):
assert count > 0, "count must be positive"
return total / count
print(average(10, 2))The assertion checks a function precondition and raises AssertionError with a message when the condition is false.
Check an internal invariant after transforming data.
Verify assumptions at function boundaries inside trusted code.
Catch impossible branches or unexpected states while debugging.
The syntax is assert expression or assert expression1, expression2. A false condition raises AssertionError; in the second form, the second expression becomes the exception value.
Follow-up: What happens under optimized execution? The assertion is skipped when __debug__ is false, so mandatory validation should use explicit conditionals and exceptions instead.
A simple assertion behaves like a conditional check guarded by __debug__; failure raises AssertionError. The message form raises AssertionError with the supplied expression as its value.
Follow-up: Why can a message expression still matter even when the condition is true? It is part of the assertion syntax, but it is only used to construct the exception when the condition fails.
Assertions are intended as convenient debugging checks. They should not replace validation of external input or any condition that must be enforced regardless of execution mode, because assertions may be disabled.
Follow-up: How would you enforce a required condition? Test it explicitly and raise an appropriate exception, such as ValueError, so the check remains active in optimized mode.
AssertionError__debug__raiseif