一、代码布局
缩进
每层缩进使用 4 个空格
断行风格
- 断行首字母与括号开启符垂直对齐
# 这是正确的例子:
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)
# 这是错误的例子,悬挂缩进,后面还有其它代码时,需要添加一层额外的缩进加以区别:
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)
# 这是错误的例子,悬挂方式首行不能有参数:
foo = long_function_name(var_one, var_two,
var_three, var_four)
if 条件断行
if (
刚好有 4 个字条,相当于一层缩进。
对于 if 条件断行,以下几种风格都可以:
- 没有额外的缩进
if (this_is_one_thing and
that_is_another_thing):
do_something()
- 添加注释加以区分
# Add a comment, which will provide some distinction in editors
# supporting syntax highlighting.
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()
多行的括号
- 括号结束符与最后行的首字符对齐,如:
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',
)
Tab 符还是空格
用空格
每行最长长度
-
所有行都不超过 80 个字符:
- 限制编辑器窗口的宽度,使能并排同时打开多个文件。
- 设置编辑器宽度( set width to 80),来避免 wrapping
-
对于较少结构限制的长文本(如 docstring 或注释),行长应限制为 72 个字符。
-
如果团队成员都同意使用长行,则可以将行长增加到不超过 100 个字符,但是 docstring 和注释还必须为 72 个字符。
-
有括号的长行可以用 implicit continuation 来断行,其它的可以用
\
来断行,如:
with open('/path/to/some/file/you/want/to/read') as file_1, \
open('/path/to/some/file/being/written', 'w') as file_2:
file_2.write(file_1.read())
操作符要和操作数在一起
# 推荐的正确的风格,这样很容易将操作符与操作数匹配:
income = (gross_wages
+ taxable_interest
+ (dividends - qualified_dividends)
- ira_deduction
- student_loan_interest)
# 这种风格现成已不推荐使用了:
income = (gross_wages +
taxable_interest +
(dividends - qualified_dividends) -
ira_deduction -
st