Python indentation in “empty lines”

2019-02-03 23:37发布

Which is preferred ("." indicating whitespace)?

A)

def foo():
    x = 1
    y = 2
....
    if True:
        bar()

B)

def foo():
    x = 1
    y = 2

    if True:
        bar()

My intuition would be B (that's also what vim does for me), but I see people using A) all the time. Is it just because most of the editors out there are broken?

9条回答
Bombasti
2楼-- · 2019-02-04 00:21

Adding proper indentation to blank lines (style A in the question) vastly improves code readability with display whitespace enabled because it makes it easier to see whether code after a blank line is part of the same indentation block or not.

For a language like Python, where there is no end statement or close bracket, I'm surprised this is not part of PEP. Editing Python with display whitespace on is strongly recommended, to avoid both trailing whitespace and mixed indentation.

Compare reading the following:

A)

def foo():
....x = 1
....y = 2
....
....if True:
........bar()

B)

def foo():
....x = 1
....y = 2

....if True:
........bar()

In A, it is far clearer that the last two lines are part of foo. This is even more useful at higher indentation levels.

查看更多
对你真心纯属浪费
3楼-- · 2019-02-04 00:22

The PEP 8 does not seem to be clear on this issue, although the statements about "blank lines" could be interpreted in favor of B. The PEP 8 style-checker (pep8.py) prefers B and warns if you use A; however, both variations are legal. My own view is that since Python will successfully interpret the code in either case that this doesn't really matter, and trying to enforce it would be a lot of work for very little gain. I suppose if you are very adamantly in favor of one or the other you could automatically convert the one to the other. Trying to fix all such lines manually, though, would be a huge undertaking and really not worth the effort, IMHO.

查看更多
姐就是有狂的资本
4楼-- · 2019-02-04 00:23

Emacs does B) for me, but I really don't think it matters. A) means that you can add in a line at the correct indentation without any tabbing.

查看更多
登录 后发表回答