What’s the difference between raise, try, and assert?

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)