Python註釋規範
注:以下內容摘自https://www.runoob.com/w3cnote/google-python-styleguide.html, 記錄於此以便查閱
文件字串
Python有一種獨一無二的的註釋方式: 使用文件字串. 文件字串是包, 模組, 類或函式裡的第一個語句. 這些字串可以通過物件的__doc__成員被自動提取, 並且被pydoc所用. (你可以在你的模組上執行pydoc試一把, 看看它長什麼樣). 我們對文件字串的慣例是使用三重雙引號"""( PEP-257 ). 一個文件字串應該這樣組織: 首先是一行以句號, 問號或驚歎號結尾的概述(或者該文件字串單純只有一行). 接著是一個空行. 接著是文件字串剩下的部分, 它應該與文件字串的第一行的第一個引號對齊. 下面有更多文件字串的格式化規範.
模組
每個檔案應該包含一個許可樣板. 根據專案使用的許可(例如, Apache 2.0, BSD, LGPL, GPL), 選擇合適的樣板.
函式和方法
下文所指的函式,包括函式, 方法, 以及生成器.
一個函式必須要有文件字串, 除非它滿足以下條件:
外部不可見
非常短小
簡單明瞭
文件字串應該包含函式做什麼, 以及輸入和輸出的詳細描述. 通常, 不應該描述"怎麼做", 除非是一些複雜的演算法. 文件字串應該提供足夠的資訊, 當別人編寫程式碼呼叫該函式時, 他不需要看一行程式碼, 只要看文件字串就可以了. 對於複雜的程式碼, 在程式碼旁邊加註釋會比使用文件字串更有意義.
關於函式的幾個方面應該在特定的小節中進行描述記錄, 這幾個方面如下文所述. 每節應該以一個標題行開始. 標題行以冒號結尾. 除標題行外, 節的其他內容應被縮排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 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