Python indentation in “empty lines”

前端 未结 10 2073
野性不改
野性不改 2020-12-29 18:29

Which is preferred (\".\" indicating whitespace)?

A)

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

B)



        
相关标签:
10条回答
  • 2020-12-29 19: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.

    0 讨论(0)
  • 2020-12-29 19:11

    B is preferred - i.e. no indentation. PEP 8 says:

    Avoid trailing whitespace anywhere. Because it's usually invisible, it can be confusing: e.g. a backslash followed by a space and a newline does not count as a line continuation marker. Some editors don't preserve it and many projects (like CPython itself) have pre-commit hooks that reject it.

    0 讨论(0)
  • 2020-12-29 19: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.

    0 讨论(0)
  • 2020-12-29 19:25

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

    0 讨论(0)
提交回复
热议问题