python注釋規(guī)范

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

文檔字符串

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

模塊

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

函數(shù)和方法

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

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

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

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

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

Args:

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

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

描述返回值的類型和語義. 如果函數(shù)返回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)段. 并且應該遵守和函數(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."""

塊注釋和行注釋

最需要寫注釋的是代碼中那些技巧性的部分. 如果你在下次 代碼審查 的時候必須解釋一下, 那么你應該現(xiàn)在就給它寫注釋. 對于復雜的操作, 應該在其操作開始前寫上若干行注釋. 對于不是一目了然的代碼, 應在其行尾添加注釋.

# 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

為了提高可讀性, 注釋應該至少離開代碼2個空格.

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

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

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