繁体   English   中英

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而言,两种样式均有效……

# 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空格缩进以外)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM