Python pylint(raising-format-tuple) 异常参数表明字符串格式化可能是有意的

Python pylint(raising-format-tuple) Exception arguments suggest string formatting might be intended

有一个简单的自定义异常 class 定义为:

class MyError(Exception):
    pass

这个调用:

foo = 'Some more info'
raise MyError("%s: there was an error", foo)

pylint 给出:

Exception arguments suggest string formatting might be intended pylint(raising-format-tuple)

这条消息是什么意思?

根据您的 Python.

版本,其中任何一项都可以修复该消息
foo = 'Some more info'
raise MyError("%s: there was an error" % foo )
raise MyError("{}: there was an error".format(foo))
raise MyError(f"{foo}: there was an error")

pylint 看到字符串中没有后续参数的 %s 标记时,将触发该消息。您将得到一个元组异常,而不是引发字符串 "Some more info: there was an error" 的异常,其中第一个元素是 ": there was an error",第二个元素是 foo 的内容。这可能不是预期的效果。

在我使用的代码中,大量使用了logging,我怀疑原作者将引发异常与混淆了。