如何向ass添加描述性字符串

2024-10-03 06:26:12 发布

您现在位置:Python中文网/ 问答频道 /正文

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

以下是我的代码及其执行:

>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

我使用的是python3.7。你知道吗

你知道为什么"hello" + a不首先作为字符串连接进行计算吗?我怎样才能做到?你知道吗

[更新]感谢您的回复,以下是我想要的:

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

Tags: and代码pymosthelloassert断言tmp
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

According to the docs,失败消息后跟逗号:

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)将被解释为一个元组,用作没有消息的条件,并且永远不会失败。你知道吗

相关问题 更多 >