关于字符串插值的未使用变量的静默PyLint警告

2024-05-20 02:03:28 发布

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

say模块为Python带来字符串插值,如下所示:

import say

def f(a):
    return say.fmt("The value of 'a' is {a}")

然而,PyLint抱怨说变量“a”从未被使用过。这是一个问题,因为我的代码广泛使用say.fmt。我怎样才能使这个警告保持沉默?


Tags: 模块ofthe字符串代码import警告return
3条回答

消除该消息的一种方法是用dummy_命名参数或在参数前面加前缀,如下所示:

import say

def f(_a):
    return say.fmt("The value of 'a' is {_a}")

有关详细信息,请参见此处:https://stackoverflow.com/a/10107410/1080804

现在有disable-possibly-unused-variable(自从pylint 2.0 was released on 2018-07-15)了,在导入say模块的文件中可以忽略它:

New possibly-unused-variable check added.

This is similar to unused-variable, the only difference is that it is emitted when we detect a locals() call in the scope of the unused variable. The locals() call could potentially use the said variable, by consuming all values that are present up to the point of the call. This new check allows to disable this error when the user intentionally uses locals() to consume everything.

For instance, the following code will now trigger this new error:

def func():
    some_value = some_call()
    return locals()

这项检查的基本原理是explicitly includes your use case,尽管人们注意到这并不是一个完美的解决方案:

It would be great to have a separate check for unused variables if locals() is used in the same scope:

def example_no_locals():
  value = 42  # pylint: disable=unused-variable

def exmaple_defined_before():
  value = 42  # pylint: disable=possibly-unused-variable
  print(locals())

def exmaple_defined_after():
  print(locals())
  value = 42  # pylint: disable=unused-variable

The benefit of this is that one can disable probably-unused-variable for a file (that has a lot of string formatting in it, or the config code example in #641) or the whole project without also loosing checks for unused-variable.

是的,你可以让pylint警告保持沉默。

有一种方法:

import say

def f(a):
    #pylint: disable=unused-argument
    return say.fmt("The value of 'a' is {a}")

或者,可以创建一个配置文件并向其中添加以下行:

[MESSAGES CONTROL]
disable=unused-argument

参考:

相关问题 更多 >