How Do I Keep Python Code Under 80 Chars Without Making It Ugly?

后端 未结 7 491
醉梦人生
醉梦人生 2021-01-31 14:27

This is a question that keeps recurring in all of my programming, python and otherwise. I really like to keep my code under 80 chars if at all possible/not horribly ugly. In a l

7条回答
  •  梦如初夏
    2021-01-31 14:45

    Some people were citing the Rectangle class as a poor example. This example in the pep8 is not the only way to do this.

    Original:

    class Rectangle(Blob):
    
        def __init__(self, width, height,
                     color='black', emphasis=None, highlight=0):
            if (width == 0 and height == 0 and
                color == 'red' and emphasis == 'strong' or
                highlight > 100):
                raise ValueError("sorry, you lose")
            if width == 0 and height == 0 and (color == 'red' or
                                               emphasis is None):
                raise ValueError("I don't think so -- values are %s, %s" %
                                 (width, height))
            Blob.__init__(self, width, height,
                          color, emphasis, highlight)
    

    This is how I would write it.

    class Rectangle(Blob):
    
        def __init__(self, width, height, color='black', emphasis=None,
                highlight=0):
            if (width == 0 and height == 0 and color == 'red' and
                    emphasis == 'strong' or highlight > 100):
                raise ValueError("sorry, you lose")
            if width == 0 and height == 0 and (color == 'red' or 
                    emphasis is None):
                msg = "I don't think so -- values are %s, %s" % (width, height)     
                raise ValueError(msg)
            Blob.__init__(self, width, height, color, emphasis, highlight)
    

    The reason being is:

    • Additional indentation to line up with '(' is a waste of time if your editor isn't doing it for you and harder to read since there is so much leading white space IMO.
    • I try to break as late as possible unless there is a compelling reason in the code logic.
    • Lining up with the '(' in this case created the exact same indentation level as the next line... very bad coincidence! Double indenting continuation lines solves this problem.
    • I prefer avoidance if the reason for having to use line continuation is trying to do too much on one line. The example here is the ValueError where they are formatting using the string format operator. I set msg instead. (Note: Format Strings using the format method are preferred, and % is deprecated since 3.1).

提交回复
热议问题