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).

assert x == 5, f"Some computationally heavy message here: {requests.get('xxx')}"

I could also write this code using an if statement:

if x != 5:
    raise AssertionError(f"Some computationally heavy message here: {requests.get('xxx')}")

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:

>>> assert 1 == 5, foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined

But:

>>> assert 5 == 5, foo

does not raise a NameError.

According to the language reference,

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

if __debug__:
    if not expression1: raise AssertionError(expression2)

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