The statement assert
can be used for checking conditions at runtime, but is removed if optimizations are requested from Python. The extended form is:
assert condition, message
and is equivalent to:
if __debug__:
if not condition:
raise AssertionError(message)
where __debug__
is True
is Python was not started with the option -O
.
So the statement assert condition, message
is similar to:
if not condition:
raise AssertionError(message)
in that both raise an AssertionError
. The difference is that assert condition, message
can be removed from the executed bytecode by optimizations (when those are enabled--by default they are not applied in CPython). In contrast, raise AssertionError(message)
will in all cases be executed.
Thus, if the code should under all circumstances check and raise an AssertionError
if the check fails, then writing if not condition: raise AssertionError
is necessary.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…