Python:避免关于参数过多的 pylint 警告 [英] Python: avoiding pylint warnings about too many arguments

查看:70
本文介绍了Python:避免关于参数过多的 pylint 警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个大的 Python 函数重构为更小的函数.例如,请考虑以下代码片段:

I want to refactor a big Python function into smaller ones. For example, consider this following code snippet:

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

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

Of course, this is a trivial example. In practice, the code is more complex. My point is that it contains many local-scope variables that would have to be passed to the extracted function, which could look like:

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

问题是 pylint 会触发关于参数过多的警告.我可以通过执行以下操作来避免警告:

The problem is that pylint would trigger a warning about too many arguments. I could avoid the warning by doing something like:

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)

但是这种方法对我来说很丑陋,它需要编写大量甚至是多余的代码.

but this approach loos ugly to me, it requires writing a lot of code that is even redundant.

有更好的方法吗?

推荐答案

第一个,玻璃市的警句:

"如果您有一个包含 10 个参数,你可能错过了一些."

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

这 10 个参数中的一些可能是相关的.将它们组合成一个对象,然后将其传递.

Some of the 10 arguments are presumably related. Group them into an object, and pass that instead.

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

Making an example up, because there's not enough information in the question to answer directly:

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

然后是你的 10 个参数函数:

Then your 10 argument function:

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)

这篇关于Python:避免关于参数过多的 pylint 警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆