python注釋規(guī)范

確保對模塊, 函數(shù), 方法和行內(nèi)注釋使用正確的風(fēng)格
參考:Python風(fēng)格規(guī)范 — Google 開源項(xiàng)目風(fēng)格指南

文檔字符串

Python有一種獨(dú)一無二的的注釋方式: 使用文檔字符串. 文檔字符串是包, 模塊, 類或函數(shù)里的第一個(gè)語句. 這些字符串可以通過對象的doc成員被自動提取, 并且被pydoc所用. (你可以在你的模塊上運(yùn)行pydoc試一把, 看看它長什么樣). 我們對文檔字符串的慣例是使用三重雙引號”“”( PEP-257 ). 一個(gè)文檔字符串應(yīng)該這樣組織: 首先是一行以句號, 問號或驚嘆號結(jié)尾的概述(或者該文檔字符串單純只有一行). 接著是一個(gè)空行. 接著是文檔字符串剩下的部分, 它應(yīng)該與文檔字符串的第一行的第一個(gè)引號對齊. 下面有更多文檔字符串的格式化規(guī)范.

模塊

每個(gè)文件應(yīng)該包含一個(gè)許可樣板. 根據(jù)項(xiàng)目使用的許可(例如, Apache 2.0, BSD, LGPL, GPL), 選擇合適的樣板.

函數(shù)和方法

下文所指的函數(shù),包括函數(shù), 方法, 以及生成器.

一個(gè)函數(shù)必須要有文檔字符串, 除非它滿足以下條件:

  1. 外部不可見
  2. 非常短小
  3. 簡單明了

文檔字符串應(yīng)該包含函數(shù)做什么, 以及輸入和輸出的詳細(xì)描述. 通常, 不應(yīng)該描述”怎么做”, 除非是一些復(fù)雜的算法. 文檔字符串應(yīng)該提供足夠的信息, 當(dāng)別人編寫代碼調(diào)用該函數(shù)時(shí), 他不需要看一行代碼, 只要看文檔字符串就可以了. 對于復(fù)雜的代碼, 在代碼旁邊加注釋會比使用文檔字符串更有意義.

關(guān)于函數(shù)的幾個(gè)方面應(yīng)該在特定的小節(jié)中進(jìn)行描述記錄, 這幾個(gè)方面如下文所述. 每節(jié)應(yīng)該以一個(gè)標(biāo)題行開始. 標(biāo)題行以冒號結(jié)尾. 除標(biāo)題行外, 節(jié)的其他內(nèi)容應(yīng)被縮進(jìn)2個(gè)空格.

Args:

列出每個(gè)參數(shù)的名字, 并在名字后使用一個(gè)冒號和一個(gè)空格, 分隔對該參數(shù)的描述.如果描述太長超過了單行80字符,使用2或者4個(gè)空格的懸掛縮進(jìn)(與文件其他部分保持一致). 描述應(yīng)該包括所需的類型和含義. 如果一個(gè)函數(shù)接受foo(可變長度參數(shù)列表)或者bar (任意關(guān)鍵字參數(shù)), 應(yīng)該詳細(xì)列出foo和**bar.</dd>

Returns: (或者 Yields: 用于生成器)

描述返回值的類型和語義. 如果函數(shù)返回None, 這一部分可以省略.

Raises:

列出與接口有關(guān)的所有異常.

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

類應(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."""

塊注釋和行注釋

最需要寫注釋的是代碼中那些技巧性的部分. 如果你在下次 代碼審查 的時(shí)候必須解釋一下, 那么你應(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個(gè)空格.

另一方面, 絕不要描述代碼. 假設(shè)閱讀代碼的人比你更懂Python, 他只是不知道你的代碼要做什么.

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

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