如何处理Pylint的“太多实例属性”消息?

时间:2014-06-26 15:27:12

标签: python instance-variables pylint code-readability code-structure

我刚尝试用Pylint lint一些代码,剩下的最后一个错误是

R0902: too-many-instance-attributes (8/7)

我理解限制实例属性数量的理由,但有七个看起来有点低。我也意识到短号不应该有最后一个字。但是,我想知道我应该做什么,而不是:

def __init__(self, output_file=None, output_dir=None):
    """
    Set the frobnicator up, along with default geometries
    """

    self.margin = 30

    self.pos = [0, 0]
    self.sep = [5, 5]

    self.cell = [20, 20]

    self.frobbr = library.Frobbr()

    page = self.frobbr.get_settings('page')

    self.lim = [page.get_width() - self.margin,
                page.get_height() - self.margin]

    self.filename = output_file
    self.moddir = output_dir

我是否应该将几何图形打包成dict,做其他事情来阻止Pylint抱怨,或者只是忽略它(我不是真的想做)?

4 个答案:

答案 0 :(得分:56)

linter的工作是让你意识到你的代码可能存在的问题,正如你在问题中所说的那样,它应该没有最后的结论。

如果您已经考虑了pylint必须说什么,并决定对于这个类,您拥有的属性是合适的(这对我来说似乎是合理的),您可以抑制错误并指出您已经通过向您的班级添加禁用评论来考虑此问题:

class Frobnicator:

    """All frobnication, all the time."""

    # pylint: disable=too-many-instance-attributes
    # Eight is reasonable in this case.

    def __init__(self):
        self.one = 1
        self.two = 2
        self.three = 3
        self.four = 4
        self.five = 5
        self.six = 6
        self.seven = 7
        self.eight = 8

这样,你既不会忽视Pylint,也不会忽视Pylint;你正在使用它作为有用但却错误的工具。

默认情况下,当您在本地禁用支票时,Pylint会生成一条信息性消息:

 Locally disabling too-many-instance-attributes (R0902) (locally-disabled)

您可以通过以下两种方式之一阻止 消息出现:

  1. 运行pylint时添加disable=标志:

    $ pylint --disable=locally-disabled frob.py 
    
  2. 将指令添加到pylintrc配置文件中:

    [MESSAGES CONTROL]
    disable = locally-disabled
    

答案 1 :(得分:15)

This is an ideological objection, but personally I tend to try to make these kind of changes as universal as possible. If 7 is not enough instances in one file, and I choose to allow it here, why not everywhere? I don't always make changes to the lint rules across the board, but I at least consider it. To that end, if you want to make an across the board change, in your .pylintrc file change Promise.resolve(resourceIds). map(function(id) { return loadResource(id); }, {concurrency: n}). catch(function(e) { //do some error handling }); in the max-attributes=7 section.

Since I think 7 is a little low across the board, I changed:

DESIGN

to

[DESIGN]
max-attributes=7

答案 2 :(得分:5)

比雷埃夫斯的答案很好。也就是说,由于你为 init 方法提供了很少的上下文,甚至不是真正的类名,所以很难肯定,但我会说文件名和moddir没有任何关系,边缘,位置,等

IO操作通常最好被隔离到函数中而不是放入方法中。它们通常有许多不同的格式和序列化选项,而且大多数时候你都不想要 将它们与您的对象逻辑(方法)混合在一起。添加一个新的IO函数更容易,它接受一些文件,字符串,blob或其他任何东西,并返回编码到其中的对象,而不是维护一个具有许多处理许多不同IO操作的方法的对象。

答案 3 :(得分:0)

通过将too-many-instance-attributes添加到项目的pylintrc.pylintrc文件中,我将完全禁用此消息,如下例所示:

[MESSAGES CONTROL]
disable=
    locally-disabled,
    locally-enabled,
    logging-format-interpolation,
    no-init,
    too-few-public-methods,
    too-many-instance-attributes,  # <-- Ensure at least this entry.
    fixme