參考
--Google Python 風(fēng)格指南 - 中文版
分號(hào)
- 不要在行尾加分號(hào), 也不要用分號(hào)將兩條命令放在同一行
行長(zhǎng)度
- 每行不超過(guò)80 個(gè)字符
<pre><code>Python 會(huì)將圓括號(hào), 中括號(hào)和花括號(hào)中的行隱式的連接起來(lái), 你可以利用這個(gè)特點(diǎn). 如
果需要, 你可以在表達(dá)式外圍增加一對(duì)額外的圓括號(hào).
Yes:
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'):
如果一個(gè)文本字符串在一行放不下, 可以使用圓括號(hào)來(lái)實(shí)現(xiàn)隱式行連接:
x = ('This will build a very long long '
'long long long long long long string')
對(duì)于注釋,如果有必要,盡可能的將整個(gè)路徑放在一行
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</code></pre>
括號(hào)
- 寧缺毋濫的使用括號(hào)
<pre><code>除非是用于實(shí)現(xiàn)行連接, 否則不要在返回語(yǔ)句或條件語(yǔ)句中使用括號(hào). 不過(guò)在元組兩邊使用
括號(hào)是可以的.
Yes:
if foo:
bar()
while x:
x = bar()
if x and y:
bar()
if not x:
bar()
return foo
for (x, y) in dict.items(): ...
No:
if (x):
bar()
if not(x):
bar()
return (foo)
4
bar()
return foo
for (x, y) in dict.items(): ...
No: if (x):
bar()
if not(x):
bar()
return (foo)</code></pre>
縮進(jìn)
- 用 4 個(gè)空格來(lái)縮進(jìn)代碼
<pre><code>絕對(duì)不要用tab, 也不要tab 和空格混用. 對(duì)于行連接的情況, 你應(yīng)該要么垂直對(duì)齊換行的
元素(見(jiàn) 行長(zhǎng)度 部分的示例), 或者使用4 空格的懸掛式縮進(jìn)(這時(shí)第一行不應(yīng)該有參數(shù)):
Yes:
Aligned with opening delimiter
foo = long_function_name(var_one, var_two,
var_three, var_four)
4-space hanging indent; nothing on first line
foo = long_function_name(
var_one, var_two, var_three,
var_four)
No:
Stuff on first line forbidden
foo = long_function_name(var_one, var_two,
var_three, var_four)
2-space hanging indent forbidden
foo = long_function_name(
var_one, var_two, var_three,
var_four)</code></pre>
空行
- 頂級(jí)定義之間空兩行, 方法定義之間空一行
<pre><code>頂級(jí)定義之間空兩行, 比如函數(shù)或者類定義. 方法定義, 類定義與第一個(gè)方法之間, 都應(yīng)該
空一行. 函數(shù)或方法中, 某些地方要是你覺(jué)得合適, 就空一行.</code></pre>
空格
- 按照標(biāo)準(zhǔn)的排版規(guī)范來(lái)使用標(biāo)點(diǎn)兩邊的空格
<pre><code>1 括號(hào)內(nèi)不要有空格.
Yes:
spam(ham[1], {eggs: 2}, [])
No:
spam( ham[ 1 ], { eggs: 2 }, [ ] )
2 不要在逗號(hào), 分號(hào), 冒號(hào)前面加空格, 但應(yīng)該在它們后面加(除了在行尾).
Yes:
if x == 4:
print x, y
x, y = y, x
No:
if x == 4 :
print x , y
x , y = y , x
3 參數(shù)列表, 索引或切片的左括號(hào)前不應(yīng)加空格.
Yes:
spam(1)
Yes:
spam (1)
Yes:
dict['key'] = list[index]
No:
dict ['key'] = list [index]
4 在二元操作符兩邊都加上一個(gè)空格, 比如賦值(=), 比較(==, <, >, !=, <>, <=, >=, in, not
in, is, is not), 布爾(and, or, not). 至于算術(shù)操作符兩邊的空格該如何使用, 需要你自己
好好判斷. 不過(guò)兩側(cè)務(wù)必要保持一致.
Yes:
x == 1
No:
x<1
5 當(dāng)’=’用于指示關(guān)鍵字參數(shù)或默認(rèn)參數(shù)值時(shí), 不要在其兩側(cè)使用空格.
Yes:
def complex(real, imag=0.0): return magic(r=real, i=imag)
No: def complex(real, imag = 0.0): return magic(r = real, i = imag)
6 不要用空格來(lái)垂直對(duì)齊多行間的標(biāo)記, 因?yàn)檫@會(huì)成為維護(hù)的負(fù)擔(dān)(適用于:, #, =等):
Yes:
foo = 1000 # comment
long_name = 2 # comment that should not be aligned
dictionary = {
"foo": 1,
"long_name": 2,
}
No:
foo = 1000 # comment
long_name = 2 # comment that should not be aligned
dictionary = {
"foo" : 1,
"long_name": 2,
}</code></pre>
Python 解釋器
- 每個(gè)模塊都應(yīng)該以#!/usr/bin/env python<version>開(kāi)頭
<pre><code>模塊應(yīng)該以一個(gè)構(gòu)造行開(kāi)始, 以指定執(zhí)行這個(gè)程序用到的Python 解釋器:
!/usr/bin/env python2.4
總是使用最特化的版本, 例如, 使用/usr/bin/python2.4, 而不是 /usr/bin/python2. 這樣,
當(dāng)升級(jí)到不同的Python 版本時(shí), 能輕松找到依賴關(guān)系, 同時(shí)也避免了使用時(shí)的迷惑. 例如,
/usr/bin/python2 是表示/usr/bin/python2.0.1 還是/usr/bin/python2.3.0</code></pre>
注釋
- 確保對(duì)模塊, 函數(shù), 方法和行內(nèi)注釋使用正確的風(fēng)格
<pre><code>文檔字符串
Python 有一種獨(dú)一無(wú)二的的注釋方式: 使用文檔字符串. 文檔字符串是包, 模塊, 類或函數(shù)
里的第一個(gè)語(yǔ)句. 這些字符串可以通過(guò)對(duì)象的doc成員被自動(dòng)提取, 并且被pydoc 所
用. (你可以在你的模塊上運(yùn)行pydoc 試一把, 看看它長(zhǎng)什么樣). 我們對(duì)文檔字符串的慣例
是使用三重雙引號(hào). 一個(gè)文檔字符串應(yīng)該這樣組織: 首先是一行以句號(hào), 問(wèn)號(hào)或驚嘆號(hào)結(jié)尾
的概述. 接著是一個(gè)空行. 接著是文檔字符串剩下的部分, 它應(yīng)該與文檔字符串的第一行的
第一個(gè)引號(hào)對(duì)齊. 下面有更多文檔字符串的格式化規(guī)范.
模塊
每個(gè)文件應(yīng)該包含下列項(xiàng), 依次是:
1 版權(quán)聲明(例如, Copyright 2008 Google Inc.)
2 一個(gè)許可樣板. 根據(jù)項(xiàng)目使用的許可(例如, Apache 2.0, BSD, LGPL, GPL), 選擇合適
的樣板
3 作者聲明, 標(biāo)識(shí)文件的原作者</code></pre>
函數(shù)和方法
<pre><code>如果不是既顯然又簡(jiǎn)短, 任何函數(shù)或方法都需要一個(gè)文檔字符串. 而且, 任何外部可訪問(wèn)的
函數(shù)或方法, 不管多短多簡(jiǎn)單, 都需要文檔字符串. 文檔字符串應(yīng)該包含函數(shù)做什么, 以及
輸入和輸出的詳細(xì)描述. 通常, 不應(yīng)該描述”怎么做”, 除非是一些復(fù)雜的算法. 對(duì)于技巧
性的代碼, 塊注釋或者行內(nèi)注釋是最重要的. 文檔字符串應(yīng)該提供足夠的信息, 當(dāng)別人編寫(xiě)
代碼調(diào)用該函數(shù)時(shí), 他不需要看一行代碼, 只要看文檔字符串就可以了. 應(yīng)該給參數(shù)單獨(dú)寫(xiě)
文檔. 在冒號(hào)后跟上解釋, 而且應(yīng)該用統(tǒng)一的懸掛式2 或4空格縮進(jìn). 文檔字符串應(yīng)該在需要
特定類型的地方指定期望的類型. “Raise:”部分應(yīng)該列出該函數(shù)可能觸發(fā)的所有異常. 生
成器函數(shù)的文檔字符串應(yīng)該用”Yields:”而非”Returns:”.
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
類(classes)
類應(yīng)該在其定義下有一個(gè)用于描述該類的文檔字符串. 如果你的類有公共屬性
(Attributes), 那么文檔中應(yīng)該有一個(gè)屬性(Attributes)段. 并且應(yīng)該遵守和函數(shù)參數(shù)相
同的格式.
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."""
塊注釋和行注釋(Block and Inline Comments)
最需要寫(xiě)注釋的是代碼中那些技巧性的部分. 如果你在下次代碼走查的時(shí)候必須解釋一
下, 那么你應(yīng)該現(xiàn)在就給它寫(xiě)注釋. 對(duì)于復(fù)雜的操作, 應(yīng)該在其操作開(kāi)始前寫(xiě)上若干行
注釋. 對(duì)于不是一目了然的代碼, 應(yīng)在其行尾添加注釋.
# 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 iff i is a power of 2
為了提高可讀性, 注釋?xiě)?yīng)該至少離開(kāi)代碼2 個(gè)空格.
另一方面, 絕不要描述代碼. 假設(shè)閱讀代碼的人比你更懂Python, 他只是不知道你的代碼要
做什么.
BAD COMMENT: Now go through the b array and make sure whenever i occurs
the next element is i+1</code></pre>
類
- 如果一個(gè)類不繼承自其它類, 就顯式的從object 繼承. 嵌套類也一樣.
<pre><code>No:
class SampleClass:
pass
class OuterClass:
class InnerClass:
pass
Yes:
class SampleClass(object):
pass
class OuterClass(object):
class InnerClass(object):
pass
class ChildClass(ParentClass):
"""Explicitly inherits from another class already."""
繼承自 object 是為了使屬性(properties)正常工作, 并且這樣可以保護(hù)你的代碼, 使其不
受Python 3000 的一個(gè)特殊的潛在不兼容性影響. 這樣做也定義了一些特殊的方法, 這些方
法實(shí)現(xiàn)了對(duì)象的默認(rèn)語(yǔ)義, 包括 new, init, delattr, getattribute,
setattr, hash, repr, and str .</code></pre>
字符串
- 用%操作符格式化字符串, 即使參數(shù)都是字符串. 不過(guò)也不能一概而論, 你需要在+和%
之間好好判定.
<pre><code>No:
x = '%s%s' % (a, b) # use + in this case
x = imperative + ', ' + expletive + '!'
x = 'name: ' + name + '; score: ' + str(n)
Yes:
x = a + b
x = '%s, %s!' % (imperative, expletive)
x = 'name: %s; score: %d' % (name, n)
避免在循環(huán)中用+和+=操作符來(lái)累加字符串. 由于字符串是不可變的, 這樣做會(huì)創(chuàng)建不必要
的臨時(shí)對(duì)象, 并且導(dǎo)致二次方而不是線性的運(yùn)行時(shí)間. 作為替代方案, 你可以將每個(gè)子串加
入列表, 然后在循環(huán)結(jié)束后用 .join 連接列表. (也可以將每個(gè)子串寫(xiě)入一個(gè)
cStringIO.StringIO 緩存中.)
No:
employee_table = ' '
for last_name, first_name in employee_list:
employee_table += '%s, %s'% (last_name, first_name)
employee_table += ' '
Yes:
items = [' ']
for last_name, first_name in employee_list:
items.append('%s, %s' % (last_name, first_name))
items.append(' ')
employee_table = ''.join(items)
為多行字符串使用三重雙引號(hào)而非三重單引號(hào). 不過(guò)要注意, 通常用隱式行連接更清晰, 因
為多行字符串與程序其他部分的縮進(jìn)方式不一致.
No:
print """This is pretty ugly.
Don't do this.
"""
Yes:
print ("This is much nicer.\n"
"Do it this way.\n")</code></pre>
TODO 注釋
- 為臨時(shí)代碼使用TODO 注釋, 它是一種短期解決方案. 不算完美, 但夠好了.
<pre><code>TODO 注釋?xiě)?yīng)該在所有開(kāi)頭處包含”TODO”字符串, 緊跟著是用括號(hào)括起來(lái)的你的名字,
email 地址或其它標(biāo)識(shí)符. 然后是一個(gè)可選的冒號(hào). 接著必須有一行注釋, 解釋要做什么. 主
要目的是為了有一個(gè)統(tǒng)一的TODO 格式, 這樣添加注釋的人就可以搜索到(并可以按需提供
更多細(xì)節(jié)). 寫(xiě)了TODO 注釋并不保證寫(xiě)的人會(huì)親自解決問(wèn)題.
TODO(kl@gmail.com): Drop the use of "has_key".
TODO(Zeke) change this to use relations.
如果你的TODO 是”將來(lái)做某事”的形式, 那么請(qǐng)確保你包含了一個(gè)指定的日期(“2009 年
11 月解決”)或者一個(gè)特定的事件(“等到所有的客戶都可以處理XML 請(qǐng)求就移除這些代
碼”).</code></pre>
導(dǎo)入格式
- 每個(gè)導(dǎo)入應(yīng)該獨(dú)占一行
<pre><code>Yes:
import os
import sys
No:
import os, sys
導(dǎo)入總應(yīng)該放在文件頂部, 位于模塊注釋和文檔字符串之后, 模塊全局變量和常量之前. 導(dǎo)
入應(yīng)該按照從最通用到最不通用的順序分組:
1 標(biāo)準(zhǔn)庫(kù)導(dǎo)入
2 第三方庫(kù)導(dǎo)入
3 應(yīng)用程序指定導(dǎo)入
4 每種分組中, 應(yīng)該根據(jù)每個(gè)模塊的完整包路徑按字典序排序, 忽略大小寫(xiě).
import foo
from foo import bar
from foo.bar import baz
from foo.bar import Quux
from Foob import ar</code></pre>
語(yǔ)句
- 通常每個(gè)語(yǔ)句應(yīng)該獨(dú)占一行
<pre><code>不過(guò), 如果測(cè)試結(jié)果與測(cè)試語(yǔ)句在一行放得下, 你也可以將它們放在同一行. 如果是if 語(yǔ)句,
只有在沒(méi)有else 時(shí)才能這樣做. 特別地, 絕不要對(duì) try/except 這樣做, 因?yàn)閠ry 和except
不能放在同一行.
Yes:
if foo: bar(foo)
No:
if foo: bar(foo)
else: baz(foo)
try: bar(foo)
except ValueError: baz(foo)
try:
bar(foo)
except ValueError: baz(foo)</code></pre>
訪問(wèn)控制
- 在 Python 中, 對(duì)于瑣碎又不太重要的訪問(wèn)函數(shù), 你應(yīng)該直接使用公有變量來(lái)取代它們,
這樣可以避免額外的函數(shù)調(diào)用開(kāi)銷. 當(dāng)添加更多功能時(shí), 你可以用屬性(property)來(lái)保
持語(yǔ)法的一致性.
<pre><code>(譯者注: 重視封裝的面向?qū)ο蟪绦騿T看到這個(gè)可能會(huì)很反感, 因?yàn)樗麄円恢北唤逃? 所有成員變量都必須是私有的! 其實(shí), 那真的是有點(diǎn)麻煩啊. 試著去
接受Pythonic 哲學(xué)吧)另一方面, 如果訪問(wèn)更復(fù)雜, 或者變量的訪問(wèn)開(kāi)銷很顯著, 那么你應(yīng)該使用像 get_foo() 和set_foo() 這樣的函數(shù)調(diào)用. 如果
之前的代碼行為允許通過(guò)屬性(property)訪問(wèn) , 那么就不要將新的訪問(wèn)函數(shù)與屬性綁定. 這樣, 任何試圖通過(guò)老方法訪問(wèn)變量的代碼就沒(méi)法運(yùn)行, 使用者
也就會(huì)意識(shí)到復(fù)雜性發(fā)生了變化.</code></pre>
命名
<pre><code>module_name, package_name,
ClassName, method_name, ExceptionName, function_name,
GLOBAL_VAR_NAME,
instance_var_name, function_parameter_name, local_var_name.
應(yīng)該避免的名稱
- 單字母名稱, 除了計(jì)數(shù)器和迭代器.
- 包/模塊名中的連字符(-)
- 雙下劃線開(kāi)頭并結(jié)尾的名稱(Python 保留, 例如init)
命名約定 - 所謂”內(nèi)部(Internal)”表示僅模塊內(nèi)可用, 或者, 在類內(nèi)是保護(hù)或私有的.
- 用單下劃線(_)開(kāi)頭表示模塊變量或函數(shù)是protected 的(使用import * from
時(shí)不會(huì)包含). - 用雙下劃線(__)開(kāi)頭的實(shí)例變量或方法表示類內(nèi)私有.
- 將相關(guān)的類和頂級(jí)函數(shù)放在同一個(gè)模塊里. 不像Java, 沒(méi)必要限制一個(gè)類一
個(gè)模塊. - 對(duì)類名使用大寫(xiě)字母開(kāi)頭的單詞(如CapWords, 即Pascal 風(fēng)格), 但是模塊
名應(yīng)該用小寫(xiě)加下劃線的方式(如lower_with_under.py). 盡管已經(jīng)有很多
現(xiàn)存的模塊使用類似于CapWords.py 這樣的命名, 但現(xiàn)在已經(jīng)不鼓勵(lì)這樣
做, 因?yàn)槿绻K名碰巧和類名一致, 這會(huì)讓人困擾.
Python 之父Guido 推薦的規(guī)范
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
Main
即使是一個(gè)打算被用作腳本的文件, 也應(yīng)該是可導(dǎo)入的. 并且簡(jiǎn)單的導(dǎo)入不應(yīng)該導(dǎo)致這
個(gè)腳本的主功能(main functionality)被執(zhí)行, 這是一種副作用. 主功能應(yīng)該放在一個(gè)
main()函數(shù)中.
在Python 中, pychecker, pydoc 以及單元測(cè)試要求模塊必須是可導(dǎo)入的. 你的代碼應(yīng)該
在執(zhí)行主程序前總是檢查 if name == 'main' , 這樣當(dāng)模塊被導(dǎo)入時(shí)主程序就不會(huì)
被執(zhí)行.
def main():
...
if name == 'main':
main()
所有的頂級(jí)代碼在模塊導(dǎo)入時(shí)都會(huì)被執(zhí)行. 要小心不要去調(diào)用函數(shù), 創(chuàng)建對(duì)象, 或者執(zhí)行那
些不應(yīng)該在使用pychecker 或pydoc 時(shí)執(zhí)行的操作.</code></pre>