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

问题描述 投票:0回答:2

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

这是我的代码及其执行:

>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

我使用的是Python 3.7。

你知道为什么

"hello" + a
不首先被评估为字符串连接吗?我怎样才能做到呢?

python python-3.x
2个回答
7
投票

根据文档,失败消息后面有一个逗号:

assert some_condition, "This is the assert failure message".

这相当于:

if __debug__:
    if not some_condition:
        raise AssertionError("This is the assert failure message")

正如评论中所述,

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


2
投票

您可以在

assert
语句后添加您的描述,并使用逗号。

如:

assert ("hello" + a) and 0, 'Your description'

结果将是:

aaabbb
Traceback (most recent call last):
  File "test.py", line 6, in <module>
    assert ("hello" + a) and 0, "Your description"
AssertionError: Your description
© www.soinside.com 2019 - 2024. All rights reserved.