python - 函数定义中星号 (*) 的替代方案

标签 python function python-3.x variadic-functions pylint

当我在函数调用中使用星号时,Pylint 会提示

def f(*args):
    # Some code

f(1, 2, 3,)

pylint 给出的输出:

pylint failed:
Used * or ** magic (star-args)

是否有在函数定义中使用 * 的替代方法,可以呈现相同的结果?

我需要代码通过 pylint 进行验证,因为这是一项学校作业。我不认为这是一个合法的警告,但我必须按照 pylint 的说法去做。

最佳答案

Pylint 高度可配置,并且在某些事情上可能会很麻烦。甚至是 star-args (W0142) rule description显示这只是一个警告:

Used * or ** magic. Used when a function or method is called using *args or **kwargs to dispatch arguments. This doesn’t improve readability and should be used with care.

只需禁用您确定使用 *args 的函数的警告即可是正确的做法,而不是尝试解决 PyLint:

def f(*args):  # pylint: disable=star-args
    # Some code

您唯一的选择是接受一个将其视为序列的参数,然后传入元组或列表:

def f(arg):
    # Some code

f((1, 2, 3))

但我严重怀疑你会因为使用# pylint disable=...而失败评论。

关于python - 函数定义中星号 (*) 的替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28915233/

相关文章:

python - Doctest python 中的私有(private)方法

python - 使用不同颜色的球在 Python/Opencv 中跟踪高尔夫球

python - 检查 Django 中是否存在模型字段

c - Unix 环境高级编程第 3 版,§7.8,未声明函数的默认返回值是 int?

c++ - 一劳永逸地理解 C 和 C++ 中 f() 和 f(void) 之间的区别

python - `python.exe -c ' 没有输出 print ("hello")'`

c++ - 函数返回负值

string - 从 Pandas 数据框中的字符串中删除 "x"个字符?

python - 读取 MIDI 文件时十六进制到整数

python - 如何根据列名属性对 Pandas 数据框进行切片?