设置为多行函数输出的变量的正确缩进是什么?
我已经看到它像这样推到等号:
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!"
)
答案 0 :(得分:2)
取决于您所说的“适当”。
就PEP 8而言,两种样式均有效……
是
# 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)
...但是您的两个示例由于其他原因均无效。
第二个缩进2个空格,而第一个缩进19个空格,但是:
每个缩进级别使用4个空格。
(目前还不太清楚是“更多缩进”应该是固定数量的缩进级别,但是我很确定这是故意的。)
但是,它也说:
4个空格规则对于续行是可选的。
当然,所有PEP 8都是可选的,特别是对于不是stdlib的代码来说,但这显然是尤其是可选的。
它们都超出了窗口的右边缘:
限制所有行最多79个字符。
要使长文本块具有较少的结构限制(文档字符串或注释),应将行长限制为72个字符。
第一个将右括号放在错误的位置:
多行构造的右花括号/括号/括号可以在列表最后一行的第一个非空白字符下对齐,如下所示:
my_list = [
1, 2, 3,
4, 5, 6,
]
...,或者可以将其排列在开始多行构造的行的第一个字符下,例如:
my_list = [
1, 2, 3,
4, 5, 6,
]
您的第二个示例正确使用了第二个版本;您的第一个示例的第一个版本有误。
但是,这里的第二种样式有一个明显的优势(正确固定为使用4个空格的缩进):将其拆分为多行的全部原因是为了使文本更适合窗口(即使您没有成功)。第一种样式在每行上浪费了额外的14个字符,因此效果较小。
还值得注意的是,black
和其他自动代码格式化程序会将您的第一个示例更改为第二个示例(同样,除了缩进4位空格之外)。