Python:避免关于参数过多的pylint警告

2024-09-29 01:22:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把一个大的Python函数重构成更小的函数。例如,请考虑以下代码段:

x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9

当然,这是一个微不足道的例子。实际上,代码更复杂。我的观点是,它包含许多必须传递给提取函数的局部范围变量,这些变量可能如下所示:

def mysum(x1, x2, x3, x4, x5, x6, x7, x8, x9):
    x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9
    return x

问题是pylint会触发关于参数过多的警告。 我可以这样做来避免警告:

def mysum(d):
    x1 = d['x1']
    x2 = d['x2']
    ...
    x9 = d['x9']
    x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9
    return x

def mybigfunction():
    ...
    d = {}
    d['x1'] = x1
    ...
    d['x9'] = x9
    x = mysum(d)

但这种方法对我来说很难看,它需要编写很多甚至是多余的代码。

有更好的办法吗?


Tags: 函数代码警告returndefx1x2x3
3条回答

您可以很容易地更改pylint中允许的最大参数数。只需打开pylintrc文件(如果还没有,则生成该文件)并更改:

最大参数=5

致:

最大参数=6#或任何适合您的值

从派林的manual

Specifying all the options suitable for your setup and coding standards can be tedious, so it is possible to use a rc file to specify the default values. Pylint looks for /etc/pylintrc and ~/.pylintrc. The --generate-rcfile option will generate a commented configuration file according to the current configuration on standard output and exit. You can put other options before this one to use them in the configuration, or start with the default values and hand tune the configuration.

你想要一个更好的方法来传递参数,还是仅仅是一种方法来阻止pylint给你带来困难?如果是后者,我似乎记得您可以通过在代码中按以下行放置pylint控制注释来停止唠叨:

#pylint: disable-msg=R0913

或:

#pylint: disable-msg=too-many-arguments

记得尽快打开它们。

在我看来,传递大量的参数和解决方案,主张将它们全部打包到某个容器参数中,除了阻止pylint唠叨您之外,并不能真正解决任何问题,本身就没有什么问题。

如果你需要传递20个参数,那么就传递它们。这可能是必需的,因为您的函数做得太多,重新分解可能会有帮助,这是您应该考虑的问题。但这不是我们真正能做的决定,除非我们看到真正的代码是什么。

首先,一个Perlis's epigrams

"If you have a procedure with 10 parameters, you probably missed some."

10个论点中的一些大概是相关的。将它们组合成一个对象,然后传递给它。

举个例子,因为问题中没有足够的信息可以直接回答:

class PersonInfo(object):
  def __init__(self, name, age, iq):
    self.name = name
    self.age = age
    self.iq = iq

那么你的10参数函数:

def f(x1, x2, name, x3, iq, x4, age, x5, x6, x7):
  ...

变成:

def f(personinfo, x1, x2, x3, x4, x5, x6, x7):
  ...

呼叫方更改为:

personinfo = PersonInfo(name, age, iq)
result = f(personinfo, x1, x2, x3, x4, x5, x6, x7)

相关问题 更多 >