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

标签 python python-3.x assert

在 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/

相关文章:

python - 使用 matplotlib 箭头进行缩放

Swift assert() 无法与 nil 进行简单比较

python - 在 centOS 7 中安装 pip

python - Google Cloud Datastore 中事务的高度一致性

Python 动态查询字符串

使用另一个过程的 Python 过程不返回任何内容

Python - 保存除大属性之外的整个类对象

c++ - 在单独的线程上删除我的 qt 类后断言失败

linux - Pthread互斥断言错误

python - 从 Python 开始 - 练习 8.14 排序算法。这个已经有名字了吗?