Ere*_*evi 5 python assert python-3.x
在Python中,我可以这样做:
assert result==100, "result should be 100"
Run Code Online (Sandbox Code Playgroud)
但这是多余的,因为我必须输入两次条件.
有没有办法让Python在断言失败时自动显示条件?
从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的答案,并找出发生在哪一行或语句上?
| 归档时间: |
|
| 查看次数: |
1756 次 |
| 最近记录: |