禁止 PyLint 报告关于字符串插值未使用变量的警告

45

say 模块将字符串插值引入了Python,就像这样:

import say

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

然而,PyLint 抱怨变量 'a' 从未被使用。这是一个问题,因为我的代码广泛使用 say.fmt。我该如何消除这个警告?


这个链接 https://docs.pylint.org/faq.html#is-it-possible-to-locally-disable-a-particular-message 有帮助吗? - Robᵩ
如果你真的想这么做,创建一个本地的.pylintrc文件来抑制那个警告。 - John Gordon
1
locals()去获取参数在say函数中使用吗?那看起来不太对劲。 - John Gordon
@JohnGordon。是的,它确实如此。而且,是的,它确实如此。 - Robᵩ
@Robᵩ:谢谢,但是我不想针对所有变量都禁用未使用的变量警告。 - Eleno
5
请注意,Python 3.6 现在包含字符串插值功能。 - Seanny123
5个回答

69

这个语句将禁用整个模块中的“unused-argument”检查。最好在此函数之后启用它。 - Vladimir Prudnikov

24

10
这种方法的缺点在于它改变了函数签名,因为在Python中,人们可以通过调用f(_a=1)来执行函数。 - Ciro Santilli OurBigBook.com
1
@CiroSantilliOurBigBook.com 我想你可以把函数的第一行写成 '_a=a',但那样有点不好。 - Cruncher

9

现在有disable-possibly-unused-variable(自2018年7月15日发布了pylint 2.0以来),您可以在导入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()
这个检查的理由明确包括了你的使用情况,尽管注意到这不是一个完美的解决方案。

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.


6
我使用这个模式:
def foo(a, b, c):
  _ = (a, b)  # unused: use these later
  return c + 1

与豁免证书相比,它不那么啰嗦,我不需要修改关键字参数名称,并且它能方便地提醒我稍后再使用这些变量。


这应该被投票得更高。我遇到了猴子补丁方法的问题,因此我不能只更改参数名称。 - Opus4210
在我看来,这比所有其他当前的解决方案都要好,因为:(1)它允许你具体地禁用a、b的pylint警告,而不是c(将来你可能有d、e、f,你不想忽略);(2)该解决方案仍然只需要一行代码(就像“# pylint: disable=unused-argument”)。 - Trevor Boyd Smith

0
我们可以通过在参数前使用“”来解决这个问题 例如: def foo(a,b): 会出现pylint问题,即'a'(未使用的参数)和'b'(未使用的参数),因此我在我的参数之前添加了“”,并且它得到了解决,如下所示 def foo(_a,_b):

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接