如果断言通过,是否评估 Python 断言消息

Is the Python assert message evaluated if the assertion passes

假设我有一个 assert 语句,其中包含计算量大的错误消息(例如,进行多个网络或数据库调用)。

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

我也可以使用 if 语句编写此代码:

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

我知道后一个选项只会在 x != 5 时评估错误消息。前一个选项呢?我想是的,但我不确定。

否,如果断言条件为真,则不会计算 , 之后的表达式:

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

但是:

>>> assert 5 == 5, foo

不提出 NameError

根据 language reference,

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

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

和一个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)

看来这是必需的行为。