...

Python代码规范之「注释」

本着规范自己写代码良好习惯的想法,整理一下Python的代码注释规范。

参考链接

Python风格规范 Google 开源项目风格指南

函数 (Function...)

一个函数必须要有文档字符串(__doc__()可调用), 除非它满足以下条件:

  • 外部不可见
  • 非常短小
  • 简单明了

标题行以冒号结尾. 除标题行外, 其他内容应被缩进2个空格。

示例代码 (Sample Code)

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:【返回值说明,包括类型和示例  Yields: 用于生成器】  
        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  

类 (Class)

  • 每一个类都应该有一个文档字符串说明文。
  • 如果有公共属性Attributes,应该按照函数格式比对去书写。

示例代码 (Sample Code)

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."""  

块注释和行注释

  • 为了在Code Review的时候防止歧义,可以在复杂的操作前块注释。
  • 为了可读性,注释起码距离代码2个空格。
  • 不要去讲解你的的代码。

示例代码 (Sample Code)

# 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 if i is 0 or a power of 2.  

补充说明

如果注释内容相当重要,使用等号隔开以更加醒目。

# =====================================  
# 请勿在此处添加 get post等app路由行为 !!!  
# =====================================  

关于Python代码注释的规范就总结到这里。

不一定全部照搬上面的规范,但一定要清晰可读性高。

共有评论(0)

登陆即可评论哦