Python 風格規范(Google)
本項目并非 Google 官方項目, 而是由國內程序員憑熱情創建和維護。
如果你關注的是 Google 官方英文版, 請移步 Google Style Guide
以下代碼中 Yes 表示推薦,No 表示不推薦。
不要在行尾加分號, 也不要用分號將兩條命令放在同一行。
每行不超過80個字符
以下情況除外:
不要使用反斜杠連接行。
Python會將 圓括號, 中括號和花括號中的行隱式的連接起來 , 你可以利用這個特點. 如果需要, 你可以在表達式外圍增加一對額外的圓括號。
推薦:
foo_bar(self, width, height, color='black', design=None, x='foo', emphasis=None, highlight=0) if (width == 0 and height == 0 and color == 'red' and emphasis == 'strong'):
如果一個文本字符串在一行放不下, 可以使用圓括號來實現隱式行連接:
x = ('這是一個非常長非常長非常長非常長 ' '非常長非常長非常長非常長非常長非常長的字符串')在注釋中,如果必要,將長的URL放在一行上。
Yes:
# See details at # http://www.example.com/us/developer/documentation/api/content/v2.0/csv_file_name_extension_full_specification.html
No:
# See details at# http://www.example.com/us/developer/documentation/api/content//# v2.0/csv_file_name_extension_full_specification.html
注意上面例子中的元素縮進; 你可以在本文的 :ref:`縮進 <indentation>`部分找到解釋.
寧缺毋濫的使用括號
除非是用于實現行連接, 否則不要在返回語句或條件語句中使用括號. 不過在元組兩邊使用括號是可以的.
Yes:
if foo: bar()while x: x = bar()if x and y: bar()if not x: bar()return foofor (x, y) in dict.items(): ...
No:
if (x): bar()if not(x): bar()return (foo)
用4個空格來縮進代碼
絕對不要用tab, 也不要tab和空格混用. 對于行連接的情況, 你應該要么垂直對齊換行的元素(見 :ref:`行長度 <line_length>` 部分的示例), 或者使用4空格的懸掛式縮進(這時第一行不應該有參數):
Yes: # 與起始變量對齊 foo = long_function_name(var_one, var_two, var_three, var_four) # 字典中與起始值對齊 foo = { long_dictionary_key: value1 + value2, ... } # 4 個空格縮進,第一行不需要 foo = long_function_name( var_one, var_two, var_three, var_four) # 字典中 4 個空格縮進 foo = { long_dictionary_key: long_dictionary_value, ... }No: # 第一行有空格是禁止的 foo = long_function_name(var_one, var_two, var_three, var_four) # 2 個空格是禁止的 foo = long_function_name( var_one, var_two, var_three, var_four) # 字典中沒有處理縮進 foo = { long_dictionary_key: long_dictionary_value, ... }
新聞熱點
疑難解答