在python assert中,如何打印断言失败时的条件?

In python assert, how to print the condition when the assertion failed?

在Python,我能做到:

assert result==100, "result should be 100"

但这是多余的,因为我必须输入两次条件。

有没有办法让Python在断言失败时自动显示条件?

来自 Jupyter notebook

回溯会发生这种情况。例如:

x = 2
assert x < 1
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-5-0662b7144a79> in <module>()
      1 x = 2
----> 2 assert x < 1

AssertionError: 

但是,最好将发生此错误的原因人性化(即用文字解释)。通常,我用它来反馈有用的信息。例如:

x = 2
assert x < 1, "Number is not less than 1: {0}".format(x)
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-4-bd4b9b15ccc2> in <module>()
      1 x = 2
----> 2 assert x < 1, "Number is not less than 1: {0}".format(x)

AssertionError: Number is not less than 1: 2

从命令行

仍然发生在回溯中。例如:

H:\>python assert.py
Traceback (most recent call last):
  File "assert.py", line 1, in <module>
    assert 2 < 1
AssertionError

适用于所有环境的解决方案

使用traceback module. For details, see answer at How to handle AssertionError in Python and find out which line or statement it occurred on?

使用纯 Python,您无法轻松地自动重现断言的条件。 pytest testing framework does exactly what you want, but the implementation for this magic is everything but trivial. In short, pytest rewrites the code of your assertions 复杂代码以捕获生成所需错误消息所需的信息。