跳到内容

f-string-in-exception (EM102)

源自 flake8-errmsg linter。

有时提供修复。

作用

检查异常构造函数中 f-string 的使用。

为什么这不好?

Python 在默认的回溯中包含 raise(并且像 Rich 和 IPython 这样的格式化程序也这样做)。

通过使用 f-string,错误消息将在回溯中重复,这会降低回溯的可读性。

示例

给定

sub = "Some value"
raise RuntimeError(f"{sub!r} is incorrect")

Python 将产生像这样的回溯

Traceback (most recent call last):
  File "tmp.py", line 2, in <module>
    raise RuntimeError(f"{sub!r} is incorrect")
RuntimeError: 'Some value' is incorrect

相反,将字符串赋值给变量

sub = "Some value"
msg = f"{sub!r} is incorrect"
raise RuntimeError(msg)

这将产生像这样的回溯

Traceback (most recent call last):
  File "tmp.py", line 3, in <module>
    raise RuntimeError(msg)
RuntimeError: 'Some value' is incorrect