say
模块将字符串插值引入了Python,就像这样:
import say
def f(a):
return say.fmt("The value of 'a' is {a}")
然而,PyLint 抱怨变量 'a' 从未被使用。这是一个问题,因为我的代码广泛使用 say.fmt
。我该如何消除这个警告?
say
模块将字符串插值引入了Python,就像这样:
import say
def f(a):
return say.fmt("The value of 'a' is {a}")
然而,PyLint 抱怨变量 'a' 从未被使用。这是一个问题,因为我的代码广泛使用 say.fmt
。我该如何消除这个警告?
是的,你可以消除pylint警告。
以下是一种方法:
import say
def f(a):
# pylint: disable=unused-argument
return say.fmt("The value of 'a' is {a}")
或者,您可以创建一个配置文件并将这些行添加到其中:
[MESSAGES CONTROL]
disable=unused-argument
参考资料:
抑制该消息的一种方法是将参数命名为dummy
或前缀为_
,例如:
import say
def f(_a):
return say.fmt("The value of 'a' is {_a}")
f(_a=1)
来执行函数。 - Ciro Santilli OurBigBook.com现在有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.
def foo(a, b, c):
_ = (a, b) # unused: use these later
return c + 1
与豁免证书相比,它不那么啰嗦,我不需要修改关键字参数名称,并且它能方便地提醒我稍后再使用这些变量。
def foo(a,b):
会出现pylint问题,即'a'(未使用的参数)和'b'(未使用的参数),因此我在我的参数之前添加了“”,并且它得到了解决,如下所示
def foo(_a,_b):
.pylintrc
文件来抑制那个警告。 - John Gordonlocals()
去获取参数在say
函数中使用吗?那看起来不太对劲。 - John Gordon