Google Python 編程風格規(guī)范

參考

--Google Python Style Guide

--Google Python 風格指南 - 中文版

分號

  • 不要在行尾加分號, 也不要用分號將兩條命令放在同一行

行長度

  • 每行不超過80 個字符
    <pre><code>Python 會將圓括號, 中括號和花括號中的行隱式的連接起來, 你可以利用這個特點. 如
    果需要, 你可以在表達式外圍增加一對額外的圓括號.
    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'):
    如果一個文本字符串在一行放不下, 可以使用圓括號來實現(xiàn)隱式行連接:
    x = ('This will build a very long long '
    'long long long long long long string')
    對于注釋,如果有必要,盡可能的將整個路徑放在一行
    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>

括號

  • 寧缺毋濫的使用括號
    <pre><code>除非是用于實現(xiàn)行連接, 否則不要在返回語句或條件語句中使用括號. 不過在元組兩邊使用
    括號是可以的.
    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>

縮進

  • 用 4 個空格來縮進代碼
    <pre><code>絕對不要用tab, 也不要tab 和空格混用. 對于行連接的情況, 你應(yīng)該要么垂直對齊換行的
    元素(見 行長度 部分的示例), 或者使用4 空格的懸掛式縮進(這時第一行不應(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>

空行

  • 頂級定義之間空兩行, 方法定義之間空一行
    <pre><code>頂級定義之間空兩行, 比如函數(shù)或者類定義. 方法定義, 類定義與第一個方法之間, 都應(yīng)該
    空一行. 函數(shù)或方法中, 某些地方要是你覺得合適, 就空一行.</code></pre>

空格

  • 按照標準的排版規(guī)范來使用標點兩邊的空格
    <pre><code>1 括號內(nèi)不要有空格.
    Yes:
    spam(ham[1], {eggs: 2}, [])
    No:
    spam( ham[ 1 ], { eggs: 2 }, [ ] )
    2 不要在逗號, 分號, 冒號前面加空格, 但應(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ù)列表, 索引或切片的左括號前不應(yīng)加空格.
    Yes:
    spam(1)
    Yes:
    spam (1)
    Yes:
    dict['key'] = list[index]
    No:
    dict ['key'] = list [index]
    4 在二元操作符兩邊都加上一個空格, 比如賦值(=), 比較(==, <, >, !=, <>, <=, >=, in, not
    in, is, is not), 布爾(and, or, not). 至于算術(shù)操作符兩邊的空格該如何使用, 需要你自己
    好好判斷. 不過兩側(cè)務(wù)必要保持一致.
    Yes:
    x == 1
    No:
    x<1
    5 當’=’用于指示關(guā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 不要用空格來垂直對齊多行間的標記, 因為這會成為維護的負擔(適用于:, #, =等):
    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 解釋器

  • 每個模塊都應(yīng)該以#!/usr/bin/env python<version>開頭
    <pre><code>模塊應(yīng)該以一個構(gòu)造行開始, 以指定執(zhí)行這個程序用到的Python 解釋器:

!/usr/bin/env python2.4

總是使用最特化的版本, 例如, 使用/usr/bin/python2.4, 而不是 /usr/bin/python2. 這樣,
當升級到不同的Python 版本時, 能輕松找到依賴關(guān)系, 同時也避免了使用時的迷惑. 例如,
/usr/bin/python2 是表示/usr/bin/python2.0.1 還是/usr/bin/python2.3.0</code></pre>

注釋

  • 確保對模塊, 函數(shù), 方法和行內(nèi)注釋使用正確的風格
    <pre><code>文檔字符串
    Python 有一種獨一無二的的注釋方式: 使用文檔字符串. 文檔字符串是包, 模塊, 類或函數(shù)
    里的第一個語句. 這些字符串可以通過對象的doc成員被自動提取, 并且被pydoc 所
    用. (你可以在你的模塊上運行pydoc 試一把, 看看它長什么樣). 我們對文檔字符串的慣例
    是使用三重雙引號. 一個文檔字符串應(yīng)該這樣組織: 首先是一行以句號, 問號或驚嘆號結(jié)尾
    的概述. 接著是一個空行. 接著是文檔字符串剩下的部分, 它應(yīng)該與文檔字符串的第一行的
    第一個引號對齊. 下面有更多文檔字符串的格式化規(guī)范.
    模塊
    每個文件應(yīng)該包含下列項, 依次是:
    1 版權(quán)聲明(例如, Copyright 2008 Google Inc.)
    2 一個許可樣板. 根據(jù)項目使用的許可(例如, Apache 2.0, BSD, LGPL, GPL), 選擇合適
    的樣板
    3 作者聲明, 標識文件的原作者</code></pre>

函數(shù)和方法

<pre><code>如果不是既顯然又簡短, 任何函數(shù)或方法都需要一個文檔字符串. 而且, 任何外部可訪問的
函數(shù)或方法, 不管多短多簡單, 都需要文檔字符串. 文檔字符串應(yīng)該包含函數(shù)做什么, 以及
輸入和輸出的詳細描述. 通常, 不應(yīng)該描述”怎么做”, 除非是一些復(fù)雜的算法. 對于技巧
性的代碼, 塊注釋或者行內(nèi)注釋是最重要的. 文檔字符串應(yīng)該提供足夠的信息, 當別人編寫
代碼調(diào)用該函數(shù)時, 他不需要看一行代碼, 只要看文檔字符串就可以了. 應(yīng)該給參數(shù)單獨寫
文檔. 在冒號后跟上解釋, 而且應(yīng)該用統(tǒng)一的懸掛式2 或4空格縮進. 文檔字符串應(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)該在其定義下有一個用于描述該類的文檔字符串. 如果你的類有公共屬性
(Attributes), 那么文檔中應(yīng)該有一個屬性(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)
最需要寫注釋的是代碼中那些技巧性的部分. 如果你在下次代碼走查的時候必須解釋一
下, 那么你應(yīng)該現(xiàn)在就給它寫注釋. 對于復(fù)雜的操作, 應(yīng)該在其操作開始前寫上若干行
注釋. 對于不是一目了然的代碼, 應(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
為了提高可讀性, 注釋應(yīng)該至少離開代碼2 個空格.
另一方面, 絕不要描述代碼. 假設(shè)閱讀代碼的人比你更懂Python, 他只是不知道你的代碼要
做什么.

BAD COMMENT: Now go through the b array and make sure whenever i occurs

the next element is i+1</code></pre>

  • 如果一個類不繼承自其它類, 就顯式的從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)正常工作, 并且這樣可以保護你的代碼, 使其不
    受Python 3000 的一個特殊的潛在不兼容性影響. 這樣做也定義了一些特殊的方法, 這些方
    法實現(xiàn)了對象的默認語義, 包括 new, init, delattr, getattribute,
    setattr, hash, repr, and str .</code></pre>

字符串

  • 用%操作符格式化字符串, 即使參數(shù)都是字符串. 不過也不能一概而論, 你需要在+和%
    之間好好判定.
    <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)中用+和+=操作符來累加字符串. 由于字符串是不可變的, 這樣做會創(chuàng)建不必要
    的臨時對象, 并且導(dǎo)致二次方而不是線性的運行時間. 作為替代方案, 你可以將每個子串加
    入列表, 然后在循環(huán)結(jié)束后用 .join 連接列表. (也可以將每個子串寫入一個
    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)
    為多行字符串使用三重雙引號而非三重單引號. 不過要注意, 通常用隱式行連接更清晰, 因
    為多行字符串與程序其他部分的縮進方式不一致.
    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 注釋

  • 為臨時代碼使用TODO 注釋, 它是一種短期解決方案. 不算完美, 但夠好了.
    <pre><code>TODO 注釋應(yīng)該在所有開頭處包含”TODO”字符串, 緊跟著是用括號括起來的你的名字,
    email 地址或其它標識符. 然后是一個可選的冒號. 接著必須有一行注釋, 解釋要做什么. 主
    要目的是為了有一個統(tǒng)一的TODO 格式, 這樣添加注釋的人就可以搜索到(并可以按需提供
    更多細節(jié)). 寫了TODO 注釋并不保證寫的人會親自解決問題.

TODO(kl@gmail.com): Drop the use of "has_key".

TODO(Zeke) change this to use relations.

如果你的TODO 是”將來做某事”的形式, 那么請確保你包含了一個指定的日期(“2009 年
11 月解決”)或者一個特定的事件(“等到所有的客戶都可以處理XML 請求就移除這些代
碼”).</code></pre>

導(dǎo)入格式

  • 每個導(dǎo)入應(yīng)該獨占一行
    <pre><code>Yes:
    import os
    import sys
    No:
    import os, sys
    導(dǎo)入總應(yīng)該放在文件頂部, 位于模塊注釋和文檔字符串之后, 模塊全局變量和常量之前. 導(dǎo)
    入應(yīng)該按照從最通用到最不通用的順序分組:
    1 標準庫導(dǎo)入
    2 第三方庫導(dǎo)入
    3 應(yīng)用程序指定導(dǎo)入
    4 每種分組中, 應(yīng)該根據(jù)每個模塊的完整包路徑按字典序排序, 忽略大小寫.
    import foo
    from foo import bar
    from foo.bar import baz
    from foo.bar import Quux
    from Foob import ar</code></pre>

語句

  • 通常每個語句應(yīng)該獨占一行
    <pre><code>不過, 如果測試結(jié)果與測試語句在一行放得下, 你也可以將它們放在同一行. 如果是if 語句,
    只有在沒有else 時才能這樣做. 特別地, 絕不要對 try/except 這樣做, 因為try 和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>

訪問控制

  • 在 Python 中, 對于瑣碎又不太重要的訪問函數(shù), 你應(yīng)該直接使用公有變量來取代它們,
    這樣可以避免額外的函數(shù)調(diào)用開銷. 當添加更多功能時, 你可以用屬性(property)來保
    持語法的一致性.
    <pre><code>(譯者注: 重視封裝的面向?qū)ο蟪绦騿T看到這個可能會很反感, 因為他們一直被教育: 所有成員變量都必須是私有的! 其實, 那真的是有點麻煩啊. 試著去
    接受Pythonic 哲學吧)另一方面, 如果訪問更復(fù)雜, 或者變量的訪問開銷很顯著, 那么你應(yīng)該使用像 get_foo() 和set_foo() 這樣的函數(shù)調(diào)用. 如果
    之前的代碼行為允許通過屬性(property)訪問 , 那么就不要將新的訪問函數(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)該避免的名稱

  1. 單字母名稱, 除了計數(shù)器和迭代器.
  2. 包/模塊名中的連字符(-)
  3. 雙下劃線開頭并結(jié)尾的名稱(Python 保留, 例如init)
    命名約定
  4. 所謂”內(nèi)部(Internal)”表示僅模塊內(nèi)可用, 或者, 在類內(nèi)是保護或私有的.
  5. 用單下劃線(_)開頭表示模塊變量或函數(shù)是protected 的(使用import * from
    時不會包含).
  6. 用雙下劃線(__)開頭的實例變量或方法表示類內(nèi)私有.
  7. 將相關(guān)的類和頂級函數(shù)放在同一個模塊里. 不像Java, 沒必要限制一個類一
    個模塊.
  8. 對類名使用大寫字母開頭的單詞(如CapWords, 即Pascal 風格), 但是模塊
    名應(yīng)該用小寫加下劃線的方式(如lower_with_under.py). 盡管已經(jīng)有很多
    現(xiàn)存的模塊使用類似于CapWords.py 這樣的命名, 但現(xiàn)在已經(jīng)不鼓勵這樣
    做, 因為如果模塊名碰巧和類名一致, 這會讓人困擾.

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
即使是一個打算被用作腳本的文件, 也應(yīng)該是可導(dǎo)入的. 并且簡單的導(dǎo)入不應(yīng)該導(dǎo)致這
個腳本的主功能(main functionality)被執(zhí)行, 這是一種副作用. 主功能應(yīng)該放在一個
main()函數(shù)中.
在Python 中, pychecker, pydoc 以及單元測試要求模塊必須是可導(dǎo)入的. 你的代碼應(yīng)該
在執(zhí)行主程序前總是檢查 if name == 'main' , 這樣當模塊被導(dǎo)入時主程序就不會
被執(zhí)行.
def main():
...
if name == 'main':
main()
所有的頂級代碼在模塊導(dǎo)入時都會被執(zhí)行. 要小心不要去調(diào)用函數(shù), 創(chuàng)建對象, 或者執(zhí)行那
些不應(yīng)該在使用pychecker 或pydoc 時執(zhí)行的操作.</code></pre>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 源地址:http://www.runoob.com/w3cnote/google-python-styleguid...
    skaiger閱讀 539評論 0 0
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,506評論 19 139
  • Python是一種對代碼風格很重視的語言,從縮進就能看出這一點,Python強調(diào)易于理解。最近在負責代碼重構(gòu)的工作...
    知曰閱讀 11,349評論 1 85
  • 21天就能養(yǎng)成一個好習慣,好多事情堅持21天之后就會發(fā)生意想不到的變化,既然如此,那我就努力多養(yǎng)成幾個好習慣:一,...
    四夕芙蓉閱讀 200評論 0 0
  • D42 我的性格是那種慢熱型的,尤其是對于不熟悉和不信任的人,話很少,幾乎是沒有什么想聊的。本來對八卦也不感興趣,...
    當額咧閱讀 324評論 2 1

友情鏈接更多精彩內(nèi)容