Skip to content
Advertisement

Is the Python assert message evaluated if the assertion passes

Let’s say I have an assert statement with a computationally heavy error message (e.g. makes several network or database calls).

JavaScript

I could also write this code using an if statement:

JavaScript

I know the latter option will only evaluate the error message if x != 5. What about the former option? I would assume so but I’m not sure.

Advertisement

Answer

No, the expression after the , is not evaluated if the asserted condition is true:

JavaScript

But:

JavaScript

does not raise a NameError.

According to the language reference,

The extended form, assert expression1, expression2, is equivalent to

JavaScript

and an if statement

[…] selects exactly one of the suites by evaluating the expressions one by one until one is found to be true […]; then that suite is executed (and no other part of the if statement is executed or evaluated)

So it seems this is the required behaviour.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement