首页 > 解决方案 > PEP 8 - 通过添加空格来对齐参数

问题描述

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

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

标签: pythonpep8

解决方案


由于维护负担,通常会避免这种对齐方式,尤其是与版本控制系统(例如 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,如果你预计代码将来不太可能被更改,或者如果你真的不在乎,那为什么不呢?:)


推荐阅读