如何在 Python 中指示多个未使用的值?

How to indicate multiple unused values in Python?

通常在 Python 中,应该使用 _ 来表示未使用的参数。

def example_basic(unused):
   pass

变成

def example_basic(_):
   pass

那么如果有多个未使用的参数,多个_不能使用,因为它们会冲突,所以使用*_

def example_multiple(unused1, unused2):
   pass

变成

def example_multiple(*_):
   pass

最后,如果有多个不相邻的参数未被使用,应该怎么办?

def example_non_adjacent(unused1, used, unused2):
    return used

使用多个 _ 仍然无效,使用 *_ 也无效,因为它们不相邻。

请注意,我非常希望更改 API,但为了这个问题,让我们假设这是不可能的。有没有一种方法可以表明它被忽略,而不用像 # pylint: disable=unused-argument 的 PyLint 或 i-dont-know-what for PyCharm?

编辑:

我在需要的地方发布了一个示例here

如果您连接几个下划线,Pylint(很可能还有您代码的其他读者)也会很高兴。如果你这样做,Pylint 不会抱怨未使用的参数:

def example_non_adjacent(_, used, __):
    return used

我同意一些评论者的看法,认为这是丑陋的,我会尽量避免它。

Pylint(我想大多数人类读者)也不会抱怨,如果你 add the prefix cb_ 到你的函数名称来传达它们是回调的事实并且你必须接收一些参数,即使你这样做不想使用它们。这对我来说似乎是更好的解决方案。

def cb_example_non_adjacent(unused1, used, unused2):
    return used

我见过使用以下习语的代码;

def example_non_adjacent(_0, used, _1, _2, _3, also_used):
    ...

如果你真的有很多未使用的变量,我觉得这很好。

也就是说,仅仅因为一个变量未被使用并不意味着如果您省略了它的专有名称,代码就更具可读性。仅当您确实认为隐藏变量名称提高可读性 and/or 理解 代码时才应这样做。

在这一点上我非常同意@jmd_dk。仅仅因为函数实际上没有引用或修改参数,并不意味着它不是 'used'。毕竟,它必须被实例化并显式传递给函数。在使用 for-loops 和列表理解时,唯一合理使用下划线作为变量名:

numbers = {_ for _ in range(10)}

for _ in numbers:
    print("Foo!")

但是您需要这样的解决方案这一事实意味着您的代码中存在设计问题。

del他们。由于垃圾收集器的工作方式,它快如闪电。

def test(test):
    del test

    print('I do not need test parameter here!')

如果您使用回调方法传递参数,请给它们一个正确的名称并 del 它们。不要将它们表示为未使用。

这是一个示例回调函数:

def handle(socket, address):
    del address  # del is as efficient as a newline ;-)

    stream = bytes()
    while True:
        chunk = socket.recv()
        if not chunk:
            break

        stream += chunk

    return stream

Pythonistas 通常不使用 _ 任何情况下都可以为参数使用下划线名称。
您可能误解了 使用 _ 下划线作为无用变量的名称。

当我们不知道如何调用它时,使用_作为变量名是可以理解的and/or它不会被使用:

# ignore variables when unpacking a tuple
def test():
    """some code here"""

    top = 10
    right = 10
    bottom = 40
    left = 10

    return top, right, bottom, left


# here we ignore right and left
top, _, bottom, _ = test()

# use top and bottom in your code