[Python-ideas] PEP 8 update on line length

Steven D'Aprano steve at pearwood.info
Tue Feb 19 19:47:34 EST 2019


On Tue, Feb 19, 2019 at 03:07:23PM +0100, simon.bordeyne wrote:

> On top of that, it's not uncommon to 
> reach 6, even 7 indentation levels. All it takes is a loop in a loop 
> (looping through an array for instance), a condition and all of that 
> inside a class' method.

Clearly that is not "all" it takes, since that's only *five* indents, 
not 6 or 7:

class X:
    def method(self):
        for a in seq:
            for b in other:
                if cond:
                    print("five indents")


[...]
> Just in that example, which is a very common 
> occurence, an doesn't warrant refactoring

Doesn't it? Maybe it does, maybe it doesn't. It depends on what's going 
on inside the method. Maybe it should be written as a function (avoiding 
one indent). Maybe the row and column processing should be factored out 
into seperate methods:

class X:
    def method(self):
        self.process_rows(seq)
    def process_rows(self, rows):
        for a in items:
            self.process_columns(a, other)
    def process_columns(self, a, cols):
        for b in cols:
            if cond:
                print("four indents")

When this is possible, it has other advantages than merely saving one 
indent: we can test and document the row and column processing 
seperately, and reduce coupling between the components. (I can 
understand the column processing without caring about the row 
processing, and visa versa.)

This is what I meant when I said that sometimes, the discipline required 
to keep to 79 columns helps give you better code. I started off wanting 
only to save an indent, but I got better documentation, better tests, 
and less coupled code that is easier to maintain.

Of course sometimes you get *worse* code by refactoring. In which case 
you shouldn't do it :-)


-- 
Steven


More information about the Python-ideas mailing list