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条回答
相关推荐>>
2楼-- · 2019-02-04 00:00

That empty line belongs to foo(), so I would consider A to be the most natural. But I guess it's just a matter of opinion.

查看更多
再贱就再见
3楼-- · 2019-02-04 00:08

vi implicitly discourages the behaviour in A because the {/} navigations no longer work as expected. git explicitly discourages it by highlighting it in red when you run git diff. I would also argue that if a line contains spaces it is not a blank line.

For that reason I strongly prefer B. There is nothing worse than expecting to skip six or so lines up with the { motion and ending up at the top of a class def.

查看更多
神经病院院长
4楼-- · 2019-02-04 00:10

I wouldn't necessarily call the first example "broken", because I know some people hate it when the cursor "jumps back" when moving the cursor up or down in code. E.g. Visual Studio (at least 2008) automatically prevents this from happening without using any whitespace characters on those lines.

查看更多
三岁会撩人
5楼-- · 2019-02-04 00:12

TextMate breaks block collapsing if you use B, and I prefer A anyway since it's more "logical".

查看更多
Evening l夕情丶
6楼-- · 2019-02-04 00:18

If you use A, you could copy paste your block in python shell, B will get unexpected indentation error.

查看更多
Juvenile、少年°
7楼-- · 2019-02-04 00:20

My experience in open-source development is that one should never leave whitespace inside blank lines. Also one should never leave trailing white-space.

It's a matter of coding etiquette.

查看更多
登录 后发表回答