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
字符串
新聞熱點
疑難解答