Python 常用 PEP8 编码规范
代码布局
缩进
每级缩进用4个空格。 括号中使用垂直隐式缩进或使用悬挂缩进。EXAMPLE:
# (垂直隐式缩进)对准左括号foo = long_function_name(var_one, var_two, var_three, var_four)# (悬挂缩进) 一般情况只需多一层缩进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)# 右括号回退my_list = [ 1, 2, 3, 4, 5, 6,]result = some_function_that_takes_arguments( 'a', 'b', 'c', 'd', 'e', 'f',)
错误示范:
# 不使用垂直对齐时,第一行不能有参数。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)# 右括号不回退,不推荐my_list = [ 1, 2, 3, 4, 5, 6, ]result = some_function_that_takes_arguments( 'a', 'b', 'c', 'd', 'e', 'f', )
最大行宽
EXAMPLE:
# 无括号续行, 利用反斜杠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())# 括号内续行, 尽量在运算符后再续行class Rectangle(Blob): def __init__(self, width, height, color='black', emphasis=None, highlight=0): if (width == 0 and height == 0 and color == 'red' and emphasis == 'strong' or highlight > 100): raise ValueError("sorry, you lose") if width == 0 and height == 0 and (color == 'red' or emphasis is None): raise ValueError("I don't think so -- values are %s, %s" % (width, height))
空行
EXAMPLE:
# 类的方法定义用单个空行分割,两行空行分割顶层函数和类的定义。class A(object): def method1(): pass def method2(): passdef method3(): pass
模块导入
EXAMPLE:
# 按模块首字母排序导入, 依此递推import activeimport adidasimport create
错误示例:
# 一行导入多模块import sys, os, knife# 不按首字母导入import createimport activeimport beyond
字符串
新闻热点
疑难解答