In defence of 80-char lines

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Apr 4 02:33:50 EDT 2013


On Wed, 03 Apr 2013 21:32:33 -0700, llanitedave wrote:

> I also tend to prefer a maximum between 110 and 120 characters.  I find
> continuation lines confusing, and when you use some third-party tools,
> such as wxPython, for example, the boilerplate code leads to some long
> lines.

Excessive boilerplate, and long lines, is a code-smell that suggests 
strongly that the code needs refactoring and/or simplifying.


> I would hate to have to break up this line, for instance:
> 
> self.mainLabel.SetFont(wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.BOLD,
> faceName = "FreeSans"))


Here, let me do that for you, with two, no, three, no FOUR levels of 
indentation :-)


                self.mainLabel.SetFont(self.label_format)


Now when you want to change the font of your labels, you can change them 
all with *one* edit. Or you can add themes to your application by reading 
style info from a config file. Even if you don't want to do that, you 
still have the benefit of much more readable code.

Clearly you have to define the label format in the class. Here's one 
simple way:

class MyClass(whatever):
    label_format = wx.Font(
        12, wx.DEFAULT, wx.NORMAL, wx.BOLD, faceName="FreeSans")

    def __init__(self, label_format=None):
        if label_format is not None:
            # Over-ride the default.
            self.label_format = label_format


Even if you don't want to do that, you can still fit it into 80 char 
lines:

        # 80 characters, not 79. Oh well.
        font = wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.BOLD, faceName="FreeSans")
        self.mainLabel.SetFont(font)


And finally, when all is said and done, the most important rule from PEP 8 
applies: know when to break the rules.



-- 
Steven



More information about the Python-list mailing list