如何在 Python 中指示多个未使用的值? [英] How to indicate multiple unused values in Python?
问题描述
通常在 Python 中,应该使用 _
来指示未使用的参数.
Normally in Python, one should use an _
to indicate an argument is unused.
def example_basic(unused):
pass
变成
def example_basic(_):
pass
那么如果有多个未使用的参数,多个_
不能使用,因为它们会冲突,所以使用*_
:
Then if there are multiple unused arguments, multiple _
s can't be used since they will conflict, so a *_
is used:
def example_multiple(unused1, unused2):
pass
变成
def example_multiple(*_):
pass
最后,如果有多个未使用的不相邻参数应该怎么做?
Finally, what should be done if there are multiple non-adjacent arguments that go unused?
def example_non_adjacent(unused1, used, unused2):
return used
使用多个 _
仍然不起作用,使用 *_
将不起作用,因为它们不相邻.
Using multiple _
s still does not work, and using *_
won't work since they're non-adjacent.
请注意,我非常希望更改 API,但为了这个问题,我们假设这是不可能的.有没有一种方法可以表明它被忽略而不使用像 # pylint: disable=unused-argument
之类的东西用于 PyLint 或 i-dont-know-what 用于 PyCharm?
Note that I would very much prefer to change the API, but for the sake of this question let's assume that's not possible. Is there a way to indicate it's ignored without using something like # pylint: disable=unused-argument
for PyLint or i-dont-know-what for PyCharm?
推荐答案
我见过使用以下习语的代码;
I've seen codes using the following idiom;
def example_non_adjacent(_0, used, _1, _2, _3, also_used):
...
如果你真的有很多未使用的变量,我觉得这很好.
which I find nice if you truly have lots of unused variables.
也就是说,仅仅因为一个变量未被使用并不意味着如果你省略了它的正确名称,代码就更易读了.只有当您确实认为隐藏变量名称提高代码的可读性和/或理解时,才应该这样做.
That said, just because a variable is unused does not mean that the code is more readable if you leave out its proper name. This should only be done if you really think that hiding the variable names improve the readability and/or understanding of the code.
这篇关于如何在 Python 中指示多个未使用的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!