如何添加描述性字符串来断言

my_*_*ion 3 python python-3.x

我喜欢在断言失败时看到一些有意义的描述。

这是我的代码及其执行:

>cat /tmp/1.py
a="aaa" + "bbb"
print(a)
assert ("hello" + a) and 0

>python /tmp/1.py
aaabbb
Traceback (most recent call last):
  File "/tmp/1.py", line 3, in <module>
    assert ("hello" + a) and 0
AssertionError
Run Code Online (Sandbox Code Playgroud)

我正在使用Python 3.7。

您知道为什么"hello" + a不首先将其评估为字符串连接吗?我该怎么做呢?

[ 更新 ]感谢您的所有答复,这是我在寻找的内容:

>cat /tmp/1.py
a="aaa" + "bbb"
print(a)
assert 0, "hello" + a
Run Code Online (Sandbox Code Playgroud)

Car*_*ate 5

根据文档,失败消息用逗号表示:

assert some_condition, "This is the assert failure message".
Run Code Online (Sandbox Code Playgroud)

这等效于:

if __debug__:
    if not some_condition:
        raise AssertionError("This is the assert failure message")
Run Code Online (Sandbox Code Playgroud)

并且如注释中所述,assert不是函数调用。不要添加括号,否则结果可能会很奇怪。assert(condition, message)将被解释为元组被用作没有消息的条件,并且永远不会失败。

  • 可能还值得注意的是,您绝对不应该假装assert是函数调用。像`assert(condition,message)`这样的语句永远不会失败。 (2认同)