?
縮進
用4個空格來縮進代碼
?
分號
不要在行尾加分號, 也不要用分號將兩條命令放在同一行。
行長度
每行不超過80個字符
以下情況除外:
l?長的導入模塊語句
l?注釋里的URL
不要使用反斜杠連接行。
Python會將?圓括號, 中括號和花括號中的行隱式的連接起來?, 你可以利用這個特點. 如果需要, 你可以在表達式外圍增加一對額外的圓括號。
?
?
?
?
命名規范
避免的情況:
- 變量名盡量有意義,長度在一個字符以上(除了計數器和迭代器)
- 包,模塊名中不要出現連字符(-)
- 不要將變量名以雙劃線開頭并結尾(如__init__為python保留特殊變量)
?
命名約定
- 用單下劃線(_)開頭表示模塊變量或函數是protected的(使用import * from時不會包含).
- 用雙下劃線(__)開頭的實例變量或方法表示類內私有.
- 將相關的類和頂級函數放在同一個模塊里. 不像Java, 沒必要限制一個類一個模塊.
- 對類名使用大寫字母開頭的單詞(如CapWords, 即Pascal風格), 但是模塊名應該用小寫加下劃線的方式(如lower_with_under.py). 盡管已經有很多現存的模塊使用類似于CapWords.py這樣的命名, 但現在已經不鼓勵這樣做, 因為如果模塊名碰巧和類名一致, 這會讓人困擾.
?
PEP8 命名:
- 函數、變量及屬性應用小寫字母拼寫,各單詞之間以下劃線相連,例如,lowercase_underscore
- 受保護的實例屬性,應該以單個下劃線開頭,例如,_leading_underscore
- 私有的實例屬性,應該以兩個下劃線開頭,例如,__double_leading_underscore
- 類與異常,應該以每個單詞首字母均大寫來命名,例如,CapitalizedWord
- 模塊級別的常量,應該全部采用大寫字母來拼寫,各單詞之間以下劃線相連,例如,ALL_CAPS
- 類中的實例方法,應該把首個參數命名為self,以表示該對象自身
- 類方法的首個參數,應該命名為cls,以表示該類自身
?
Python之父Guido推薦的規范
(所謂"內部(Internal)"表示僅模塊內可用, 或者, 在類內是保護或私有的
Type | Public | Internal |
Modules | lower_with_under | _lower_with_under |
Packages | lower_with_under | ? |
Classes | CapWords | _CapWords |
Exceptions | CapWords | ? |
Functions | lower_with_under() | _lower_with_under() |
Global/Class Constants | CAPS_WITH_UNDER | _CAPS_WITH_UNDER |
Global/Class Variables | lower_with_under | _lower_with_under |
Instance Variables | lower_with_under | _lower_with_under (protected) or __lower_with_under (private) |
Method Names | lower_with_under() | _lower_with_under() (protected) or __lower_with_under() (private) |
Function/Method Parameters | lower_with_under | ? |
Local Variables | lower_with_under | ? |
?
?
注釋
確保對模塊, 函數, 方法和行內注釋使用正確的風格
文檔字符串
Python有一種獨一無二的的注釋方式: 使用文檔字符串. 文檔字符串是包, 模塊, 類或函數里的第一個語句. 這些字符串可以通過對象的__doc__成員被自動提取, 并且被pydoc所用. (你可以在你的模塊上運行pydoc試一把, 看看它長什么樣). 我們對文檔字符串的慣例是使用三重雙引號"""(?PEP-257?). 一個文檔字符串應該這樣組織: 首先是一行以句號, 問號或驚嘆號結尾的概述(或者該文檔字符串單純只有一行). 接著是一個空行. 接著是文檔字符串剩下的部分, 它應該與文檔字符串的第一行的第一個引號對齊. 下面有更多文檔字符串的格式化規范.
函數和方法
下文所指的函數,包括函數, 方法, 以及生成器.
一個函數必須要有文檔字符串, 除非它滿足以下條件:
l?外部不可見
l?非常短小
l?簡單明了
文檔字符串:
應該包含函數做什么, 以及輸入和輸出的詳細描述. 通常, 不應該描述"怎么做", 除非是一些復雜的算法. 文檔字符串應該提供足夠的信息, 當別人編寫代碼調用該函數時, 他不需要看一行代碼, 只要看文檔字符串就可以了. 對于復雜的代碼, 在代碼旁邊加注釋會比使用文檔字符串更有意義.
關于函數的幾個方面應該在特定的小節中進行描述記錄, 這幾個方面如下文所述. 每節應該以一個標題行開始. 標題行以冒號結尾. 除標題行外, 節的其他內容應被縮進2個空格.
Args:
列出每個參數的名字, 并在名字后使用一個冒號和一個空格, 分隔對該參數的描述.如果描述太長超過了單行80字符,使用2或者4個空格的懸掛縮進(與文件其他部分保持一致). 描述應該包括所需的類型和含義. 如果一個函數接受*foo(可變長度參數列表)或者**bar (任意關鍵字參數), 應該詳細列出*foo和**bar.
Returns: (或者 Yields: 用于生成器)
描述返回值的類型和語義. 如果函數返回None, 這一部分可以省略.
Raises:
列出與接口有關的所有異常.
示例:
def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
????"""Fetches rows from a Bigtable.
?
????Retrieves rows pertaining to the given keys from the Table instance
????represented by big_table. ?Silly things may happen if
????other_silly_variable is not None.
?
????Args:
????????big_table: An open Bigtable Table instance.
????????keys: A sequence of strings representing the key of each table row
????????????to fetch.
????????other_silly_variable: Another optional variable, that has a much
????????????longer name than the other args, and which does nothing.
?
????Returns:
????????A dict mapping keys to the corresponding table row data
????????fetched. Each row is represented as a tuple of strings. For
????????example:
?
????????{'Serak': ('Rigel VII', 'Preparer'),
?????????'Zim': ('Irk', 'Invader'),
?????????'Lrrr': ('Omicron Persei 8', 'Emperor')}
?
????????If a key from the keys argument is missing from the dictionary,
????????then that row was not found in the table.
?
????Raises:
????????IOError: An error occurred accessing the bigtable.Table object.
????"""
????pass
?
類
類應該在其定義下有一個用于描述該類的文檔字符串. 如果你的類有公共屬性(Attributes), 那么文檔中應該有一個屬性(Attributes)段. 并且應該遵守和函數參數相同的格式.
示例:
class SampleClass(object):
????"""Summary of class here.
?
????Longer class information....
????Longer class information....
?
????Attributes:
????????likes_spam: A boolean indicating if we like SPAM or not.
????????eggs: An integer count of the eggs we have laid.
????"""
?
????def __init__(self, likes_spam=False):
????????"""Inits SampleClass with blah."""
????????self.likes_spam = likes_spam
????????self.eggs = 0
?
????def public_method(self):
????????"""Performs operation blah."""
?
塊注釋和行注釋
最需要寫注釋的是代碼中那些技巧性的部分. 如果你在下次?代碼審查?的時候必須解釋一下, 那么你應該現在就給它寫注釋. 對于復雜的操作, 應該在其操作開始前寫上若干行注釋. 對于不是一目了然的代碼, 應在其行尾添加注釋.
# We use a weighted dictionary search to find out where i is in
# the array. ?We extrapolate position based on the largest num
# in the array and the array size and then do binary search to
# get the exact number.
?
if i & (i-1) == 0: ???????# true if i is a power of 2
為了提高可讀性, 注釋應該至少離開代碼2個空格.
?
模塊導入
Import 語句應該按順序劃分成三個部分,分別表示標準庫模塊,第三方模塊及自用模塊,在每個部分中,各import語句應該按模塊的字母順序來排列
其他建議
?
類
如果一個類不繼承自其它類, 就顯式的從object繼承. 嵌套類也一樣
繼承自?object?是為了使屬性(properties)正常工作, 并且這樣可以保護你的代碼, 使其不受Python 3000的一個特殊的潛在不兼容性影響. 這樣做也定義了一些特殊的方法, 這些方法實現了對象的默認語義, 包括?__new__, __init__, __delattr__, __getattribute__, __setattr__, __hash__, __repr__, and __str__?
?
字符串
避免在大循環中用+和+=拼接字符串,這樣做會創建不必要的臨時對象,且會使得代碼運行時間以二次方增長,作為替代方案, 你可以將每個子串加入列表, 然后在循環結束后用?.join?連接列表.?
?
?
使用with語句
為了確保文件句柄能在不用時關閉,請使用with...as語句
with open("hello.txt") as hello_file:
????for line in hello_file:
????????print line?