Pylint false positives

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Aug 18 21:13:03 EDT 2018


On Sun, 19 Aug 2018 00:11:30 +0300, Marko Rauhamaa wrote:

> In Python programming, I mostly run into closures through inner classes
> (as in Java).

Inner classes aren't closures.

Its also quite expensive to be populating your application with lots of 
classes used only once each, which is a common pitfall when using inner 
classes. Memory is cheap, but it's not so cheap that we ought to just 
profligately waste it needlessly.


> populating an object with fields (methods) in a loop is very 
> rarely a good idea.

Of course it is *rarely* a good idea, because it is rare for the fields 
to be either identical (except for the name) or algebraically derived 
from the loop counter. Using a dict in place of an object, it's hard to 
see any elegant way to move this into a loop:

{'a': 10, 'B': -2, 'c': 97, 'd': None, 'h': 'surprise!', 'm': []}


and so we should not. Any such loop would surely be complex, complicated, 
obscure, even obfuscated compared to writing out the dict/object 
assignments manually.

But in context, we're not discussing the millions of cases were the 
methods/fields are naturally written out manually.

So give me credit for not being a total idiot. Not once in this thread 
have I suggested that we ought to run through all our projects, changing 
every class and putting all methods inside factories. It goes without 
saying that under usual, common circumstances we write out our methods 
manually. I was speaking about one very specific case:


* You have a fair number of identical methods in a single class.


Our choices are, (1):

- write a large block of mindless boilerplate;

- even worse, have that same boilerplate but split it up,
  scattering the individual methods all around the class;

- either way, it is repetitious and error-prone, with
  obvious reliability and maintenance problems:

    def foo(self):
        return NotImplemented

    def bar(self):
        return NotImplemented

    def baz(self):
        return NonImplemented



or, (2):

- automate the repetitious code by moving the method 
  definitions into a loop.


Obviously there is some (small) complexity cost to automating it. I 
didn't specify what a fair number of methods would be (my example showed 
four, but that was just an illustration, not real code). In practice I 
wouldn't even consider this for three methods. Six or eight seems like a 
reasonable cut-of point for me, but it depends on the specifics of the 
code and who I was writing it for.

(Note that this makes me much more conservative than the usual advice 
given by system admins, when you need to do the same thing for the third 
time, write a script to automate it.)



-- 
Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson




More information about the Python-list mailing list