CKTIS / Python
AssertionError — a failed assertion
AssertionError is a built-in exception raised when an assert statement's condition is false. Assertions check internal program assumptions, not mandatory input validation: optimization can remove them.
Version: Python 3.14; repository image, production runtime not attested
Syntax
assert condition
assert condition, message
raise AssertionError(message)AssertionError is a built-in exception class derived from Exception. When assertions are enabled, assert condition tests the condition's truth value and raises AssertionError if it is false. The form assert condition, message passes the value of message to the exception constructor; the message expression is evaluated only when the condition fails.
An assertion expresses a programmer's assumption about internal program state. In the example, first_item assumes that the list is not empty. Calling it with [] violates that assumption, and except AssertionError as exc catches the exception and prints its type and message. Catching it here demonstrates the exception rather than fixing its cause.
Do not use assert for mandatory user-input validation or permission checks. With optimization, such as -O, assert statements are omitted: neither the condition nor the message is evaluated. Do not put operations required for the program to work inside them. Write mandatory checks using if with an explicit raise, choosing an appropriate exception, such as ValueError for an inappropriate argument value.
You can also explicitly execute raise AssertionError(message); that statement is not removed by optimization. When diagnosing the error, inspect the violated assumption and the code that produced the unexpected state instead of merely deleting the assertion.
Examples
def first_item(items):
assert len(items) > 0, "items must not be empty"
return items[0]
try:
first_item([])
except AssertionError as exc:
print(type(exc).__name__)
print(str(exc))Result
AssertionError items must not be empty
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.