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

Ere*_*evi 5 python assert python-3.x

在Python中,我可以这样做:

assert result==100, "result should be 100"
Run Code Online (Sandbox Code Playgroud)

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

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

jpp*_*jpp 5

从Jupyter笔记本

这发生在回溯中。例如:

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: 
Run Code Online (Sandbox Code Playgroud)

但是,优良作法是人性化(即用言语解释)为什么会发生此错误。通常,我用它来反馈有用的信息。例如:

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
Run Code Online (Sandbox Code Playgroud)

从命令行

追溯仍然会发生这种情况。例如:

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

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

使用回溯模块。有关详细信息,请参见如何在Python中处理AssertionError的答案,并找出发生在哪一行或语句上?


seb*_*sgo 5

使用纯Python,您无法轻松地自动重现断言的条件.该pytest测试框架不正是你想要什么,但对于这个神奇的实现就是一切,但微不足道.简而言之,pytest 将断言的代码重写为复杂代码,以捕获生成所需错误消息所需的信息.