在 Python 中,我可以这样做:
assert result==100, "result should be 100"
但这是多余的,因为我必须输入两次条件。
有没有办法告诉 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:
但是,将发生此错误的原因人性化(即用文字解释)是一种很好的做法。通常,我用它来反馈有用的信息。例如:
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模块。详情请查看How to handle AssertionError in Python and find out which line or statement it occurred on?的回答
关于python - 在python断言中,断言失败时如何打印条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48783271/