Python断言带有变量的字符串



如果我在python 中执行以下操作

i = 0
assert i == 1, f"expected 1, got {i}"

断言消息是

Traceback(最后一次调用(:。。。断言i==1;预期为1,得到{i}";

如何让它显示expected 1, got 0?它似乎没有首先展开动态字符串,而是将其视为文字。

如果您只想打印单行,而不需要整个回溯,这里有一种处理方法:

import sys
i = 0
try:
assert i == 1, f"expected 1, got {i}"
except AssertionError as e:
print(e)
# print(e, file=sys.stderr) # to print to stderr
sys.exit(1) # exit program with error

您还可以截取系统exceptbook或类似的内容,并更改回溯的打印方式。

以下是一本优秀的书:

import sys
def assertion_excepthook(type, value, traceback):
if type is AssertionError:
print(value)
# with line number:
print(f"{traceback.tb_lineno}: {value}")
else:
sys.__excepthook__(type, value, traceback)
sys.excepthook = assertion_excepthook
i = 0
assert i == 1, f"expected 1, got {i}"

此解决方案的开销稍大,但这意味着您不必执行多个try/except块。

最新更新