PEP 8 - 通过添加空格来对齐参数

PEP 8 - Aligning parameters by adding whitespace

我倾向于通过以下(非常规)方式添加空格来对齐我的代码。

def my_demo_function(input1, input2, input3):
    print(input1 + input2 + input3)

my_demo_function("some long string", "some other string", "some final string")
my_demo_function("other string",     "another string",    "another other string")
my_demo_function("blah1",            "blah2 string",      "blah3" )

PEP-8 似乎没有讨论这种(hack?)对齐方式。有什么理由我不应该在我的代码中这样做吗?我可以设想这样一种情况,即阅读它的人不会向右滚动并错过一些重要的东西。

由于维护负担,通常会避免这种对齐方式,尤其是在与版本控制系统结合使用时,例如 git。

例如,假设您想稍后更改代码中的某些字符串,例如,"some long string""some very long string"。那么你的代码就变成了

my_demo_function("some very long string", "some other string", "some final string")
my_demo_function("other string",     "another string",    "another other string")
my_demo_function("blah1",            "blah2 string",      "blah3" )

如果您不相应地更改其他行。

现在要保持对齐,您需要在第二行和第三行添加更多空格,这可能会很麻烦(也可能不会,具体取决于您的文本编辑器)。

更重要的是,假设您正在使用 git。唯一“有意义”的变化发生在第一行。但是,当您修改另外两行时,git 会记录这两行也发生了变化,尽管这种变化纯粹是表面上的变化。当您稍后查看 git 历史记录时,这可能会使事情变得复杂。

话虽如此,这完全取决于您。如果您不使用 git,如果您预计代码将来不太可能更改,或者您真的不在乎,那么为什么不呢? :)

提到了为什么代码不应该那样对齐的确切原因——更改代码时保持对齐的维护开销,以及它如何影响版本控制系统中的差异。

PEP-8 doesn't seem to discuss this sort of (hack?) alignment.

PEP8 绝对是。在 Whitespace in Expressions and StatementsPet Peeves 部分:

Avoid extraneous whitespace in the following situations:

More than one space around an assignment (or other) operator to align it with another:

# Correct:
x = 1
y = 2
long_variable = 3
# Wrong:
x             = 1
y             = 2
long_variable = 3