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

Mat*_*one 5 python exception pylint

使用一个简单的自定义异常类定义为:

class MyError(Exception):
    pass
Run Code Online (Sandbox Code Playgroud)

这个电话:

foo = 'Some more info'
raise MyError("%s: there was an error", foo)
Run Code Online (Sandbox Code Playgroud)

pylint 给出:

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

这个消息是什么意思?

Mat*_*one 10

根据您的 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")
Run Code Online (Sandbox Code Playgroud)

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

在我使用的代码中,广泛使用了logging,我怀疑原作者将异常引发与延迟日志记录混淆了。

  • 您的评论“_我怀疑原作者将异常引发与惰性日志记录混淆了_”。完全钉牢了! (3认同)