代码布局
- 缩进
每级缩进用4个空格。
括号中使用垂直隐式缩进或使用悬挂缩进。后者应注意第一行要没有参数,后续行要有缩进。
- Yes
# 对准左括号
foo = long_function_name(var_one, var_two,
var_three, var_four)
# 不对准左括号,但加多一层缩进,以和后面内容区别。
def long_function_name(
var_one, var_two, var_three,
var_four):
print(var_one)
# 悬挂缩进必须加多一层缩进.
foo = long_function_name(
var_one, var_two,
var_three, var_four)
- No
# 不使用垂直对齐时,第一行不能有参数。
foo = long_function_name(var_one, var_two,
var_three, var_four)
# 参数的缩进和后续内容缩进不能区别。
def long_function_name(
var_one, var_two, var_three,
var_four):
print(var_one)
四个空格的规则是对续行可选的。
# 悬挂缩进不一定是4个空格
foo = long_function_name(
var_one, var_two,
var_three, var_four)
if语句跨行时,两个字符关键字(比如if)加上一个空格,再加上左括号构成了很好的缩进。后续行暂时没有规定,至少有如下三种格式,建议使用第三种。
# 没有额外缩进,不是很好看,个人不推荐.
if (this_is_one_thing and
that_is_another_thing):
do_something()
# 添加注释
if (this_is_one_thing and
that_is_another_thing):
# Since both conditions are true, we can frobnicate.
do_something()
# 额外添加缩进,推荐。
# Add some extra indentation on the conditional continuation line.
if (this_is_one_thing
and that_is_another_thing):
do_something()
右边括号也可以另起一行。有两种格式,建议第2种。
# 右括号不回退,个人不推荐
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',
)
未完待续……
参考链接:开源中国https://my.oschina.net/u/1433482/blog/464444