Python Assert Statements
Learn how Python's assert statement checks assumptions and raises AssertionError when an expected condition is false, including when assert is appropriate and when explicit error handling is required.
Basic
Sometimes a program reaches a point where a condition should already be true. Python's
assert statement lets you state that assumption directly. If the condition is false, Python raises
AssertionError.
The basic form
|
|
When each condition is true, execution continues normally.
The expression after
assert is evaluated. A true result lets the program continue. A false result causes an
AssertionError to be raised.
A failed assertion
|
|
A false assertion raises AssertionError, and the optional message becomes the exception's message.
The optional second expression supplies information when the assertion fails:
assert condition, message. The message is evaluated only when the assertion fails.
Assert an internal assumption
|
|
Assertions can document an assumption that the program expects to hold at a particular point.
This is most useful for assumptions about the program's own state or a programmer-facing invariant. It makes an unexpected state fail close to where the assumption was made.
Assert is not input validation
|
|
Use explicit error handling when invalid external input must be rejected, rather than relying on assert.
The distinction matters because Python can omit
assert statements when optimization is requested. An input or configuration check should therefore use normal control flow and an explicit exception when it must always run.
The optional message
|
|
The comma form lets you attach a useful diagnostic message to a failed assertion.
Assertions and optimization
|
|
Normally __debug__ is true. Python can disable assert statements when started with -O.
Python's reference semantics describe an
assert statement as a debugging assertion. In normal execution, a failed assertion raises
AssertionError. Under optimization with
-O, Python sets
__debug__ false and emits no code for
assert statements.
A useful mental model
Think of
assert as a statement that says, “At this point in the program, I expect this to be true.” It is a programmer-facing diagnostic tool, not a general-purpose way to handle bad input.
Thanks for your feedback.
Mark this learning resource complete to track your learning progress.