Python 分配给多行函数值的变量的正确缩进?

Python proper indentation for variable assigned to value of multi-line function?

设置为多行函数输出的变量的正确缩进是什么?

我看到它像这样推到等号处:

dept_alias_valid = RegexValidator(
                  '^(?!.*--)(?!.*__)(?!.*-_)(?!.*_-)([@]+[a-z][a-z\-_]+[a-z]+)$', 
                  "Alias must: start with @ and the remainder can contain only lowercase letters a-z _underscores -dashes with neither trailing nor back-to-back special characters and spaces are right out!"
                   )

而且我也看到过这样的:

dept_alias_valid = RegexValidator(
  '^(?!.*--)(?!.*__)(?!.*-_)(?!.*_-)([@]+[a-z][a-z\-_]+[a-z]+)$', 
  "Alias must: start with @ and the remainder can contain only lowercase letters a-z _underscores -dashes with neither trailing nor back-to-back special characters and spaces are right out!"
)

取决于你所说的“适当”是什么意思。


PEP 8而言,两种样式都有效…

Yes

# Aligned with opening delimiter.
foo = long_function_name(var_one, var_two,
                         var_three, var_four)

# More indentation included to distinguish this from the rest.
def long_function_name(
        var_one, var_two, var_three,
        var_four):
    print(var_one)

# Hanging indents should add a level.
foo = long_function_name(
    var_one, var_two,
    var_three, var_four)

…但是你的两个例子都因为其他原因无效。


第二个缩进2spaces,而第一个缩进19spaces,但是:

Use 4 spaces per indentation level.

完全 不清楚“更多缩进”应该是固定数量的缩进级别,但我很确定这是意图。)

但是,它还说:

The 4-space rule is optional for continuation lines.

当然,所有 PEP 8 都是可选的,尤其是对于不适用于 stdlib 的代码,但这显然 特别是 可选。


而且它们都超出了 window 的右边缘:

Limit all lines to a maximum of 79 characters.

For flowing long blocks of text with fewer structural restrictions (docstrings or comments), the line length should be limited to 72 characters.


而第一个将右括号放在错误的位置:

The closing brace/bracket/parenthesis on multiline constructs may either line up under the first non-whitespace character of the last line of list, as in:

my_list = [
    1, 2, 3,
    4, 5, 6,
    ]

… or it may be lined up under the first character of the line that starts the multiline construct, as in:

my_list = [
    1, 2, 3,
    4, 5, 6,
]

你的第二个例子是正确的第二个版本;你的第一个例子第一个版本是错误的。


然而,第二种风格有一个明显的优势(正确固定为使用 4-space 缩进):将其拆分为多行的全部原因是为了更容易将文本放入 window(即使您没有成功)。第一种样式每行多浪费了 14 个字符,因此效果较差。

还值得注意的是,black 和其他自动代码格式化程序会将您的第一个示例更改为您的第二个示例(同样,4-space 缩进除外)。