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

后端 未结 7 501
醉梦人生
醉梦人生 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:53

    Your code style seems to insist that if you break a line inside a parenthesis, lines below need to line up with it:

    self.SomeLongLongName = SomeLongLongName.SomeLongLongName(some_obj,
                                                              self.user1
                                                              self.user2)
    

    If you are willing to drop this requirement, you can format the code as follows, where continued lines have a fixed double indent:

    self.SomeLongLongName = SomeLongLongName.SomeLongLongName(
            some_obj, self.user1, self.user2)
    

    This avoids writing code down the right-hand margin on the page, and is very readable once you are used to it. It also has the benefit that if you modify the name of "SomeLongLongName", you don't have to re-indent all of the following lines. A longer example would be as follows:

    if SomeLongLongName.SomeLongLongName(
            some_obj, self.user1, self.user2):
        foo()
    else:     
        bar()
    

    The double indent for continued lines allows you to visually separate them from lines indented because they are in an if or else block.

    As others have noted, using shorted names also helps, but this isn't always possible (such as when using an external API).

提交回复
热议问题