assert — Expert Examples
Debugging aid that tests a condition and raises AssertionError if false
Assert bytecode and -O flag
How assert compiles and how optimization removes it.
python
import dis def with_assert(): x = 42 assert x > 0, "must be positive" return x print("Assert bytecode:") dis.dis(with_assert) # The assert compiles to: # LOAD x, LOAD 0, COMPARE_OP >, POP_JUMP_IF_TRUE (skip) # LOAD AssertionError, LOAD "message", CALL, RAISE # # With python -O, the entire block is removed import sys print(f"\n__debug__ = {__debug__}") print(f"Optimization level: {sys.flags.optimize}")
assert compiles to a conditional that loads AssertionError and raises it. When Python runs with -O flag, __debug__ is False and all assert statements are stripped from the bytecode entirely.
Want to try these examples interactively?
Open Expert Playground