PEPs(Python Enhancement Proposals) 是增强Python可读的建议规范,描述和记录了Python语言的发展方式。它还为Pythonic方式编写代码提供了一个参考点。当然这只是Python代码的样式指南。
PEPs旨在帮助开发人员能够写出更加易读的代码。
一、代码布局
1、每个缩排级别应该使用4个空格
连续行建议:
Continuation lines should align wrapped elements either vertically using Python's implicit line joining inside parentheses, brackets and braces, or using a hanging indent [7]. When using a hanging indent the following should be considered; there should be no arguments on the first line and further indentation should be used to clearly distinguish itself as a continuation line.
连续行应该对齐封装的元素,或者垂直对齐封装的元素。在Python中,通过使用小括号、中括号、大括号或者悬挂缩进来表示隐式行(不用特别添加反斜杠'\')。在使用悬挂缩进时,应该保证第一行没有任何参数元素,并且应该中更多的缩进来明确区分所在字符串都是同一行,是连续内容行。
正确实例:
1)垂直对齐
2)悬挂缩进
# Aligned with opening delimiter.
foo = long_function_name(var_one, var_two,
var_three, var_four)
# Hanging indents should add a level.
foo = long_function_name(
var_one, var_two,
var_three, var_four)
3)悬挂缩进,为保证与后续代码分隔,可以增加更多缩进
# 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 indent 悬挂缩进
Hanging indentation is a type-setting style where all the lines in a paragraph are indented except the first line. In the context of Python, the term is used to describe a style where the opening parenthesis of a parenthesized statement is the last non-whitespace character of the line, with subsequent lines being indented until the closing parenthesis.
悬挂缩进是一种类型设置样式,其中段落中的所有行都应该缩进,除了第一行。在Python的上下文中,悬挂缩进这个术语用来描述一种样式,其中,带括号语句的左括号应该是该行的最后一个非空格字符,随后的行被缩进,直到右括号
The closing brace/bracket/parenthesis on multiline constructs may either line up under the first non-whitespace character of the last line of lis,or it may be lined up under the first character of the line that starts the multiline construct,
多行结构中的右小括号、右中括号、右大括号可以排列在列表的最后一行的一个非空白字符串下,或者在多行构建语句的行的第一个字符串下排列
正确实例:
my_list = [
1, 2, 3,
4, 5, 6,
]
result = some_function_that_takes_arguments(
'a', 'b', 'c',
'd', 'e', 'f',
)
或者
my_list = [
1, 2, 3,
4, 5, 6,
]
result = some_function_that_takes_arguments(
'a', 'b', 'c',
'd', 'e', 'f',
)