CKTIS / Python
Keyword assert
Test a debugging invariant with a truth test when `__debug__` is true.
Version: Python 3.14; repository image, production runtime not attested
Syntax
assert expression, messageTest a debugging invariant with a truth test when __debug__ is true.
A false expression evaluates the optional message and raises AssertionError with that message. With -O the compiler removes the assertion, including side effects in either expression.
The example runs identical assertions under compile optimization levels zero and one.
Examples
source = "seen.append(1)\nassert check(), message()"
for level in (0, 1):
seen = []
def check():
seen.append("check")
return False
def message():
seen.append("message")
return "limit"
try:
exec(compile(source, "<example>", "exec", optimize=level))
except AssertionError as error:
seen.append(str(error))
print(seen)
Result
[1, 'check', 'message', 'limit'] [1]
The example runs identical assertions under compile optimization levels zero and one.