How to deal with Pylint's "too-many-instance-attributes" message?

Inductiveload picture Inductiveload · Jun 26, 2014 · Viewed 44.8k times · Source

I have just tried to lint some code with Pylint, and the last remaining error is

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

I understand the rationale behind limiting the number of instance attributes, but seven seems a bit low. I also realise that the linter should not have the last word. However, I would like to know what I should be doing instead of:

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

Should I package the geometries up into a dict, do something else to stop Pylint complaining, or just ignore it (which I don't really want to do)?

Answer

Zero Piraeus picture Zero Piraeus · Jun 26, 2014

A linter's job is to make you aware of potential issues with your code, and as you say in your question, it should not have the last word.

If you've considered what pylint has to say and decided that for this class, the attributes you have are appropriate (which seems reasonable to me), you can both suppress the error and indicate that you've considered the issue by adding a disabling comment to your class:

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

That way, you're neither ignoring Pylint nor a slave to it; you're using it as the helpful but fallible tool it is.

By default, Pylint will produce an informational message when you locally disable a check:

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

You can prevent that message from appearing in one of two ways:

  1. Add a disable= flag when running pylint:

    $ pylint --disable=locally-disabled frob.py 
    
  2. Add a directive to a pylintrc config file:

    [MESSAGES CONTROL]
    disable = locally-disabled