python注释google规范 - Go语言中文社区

python注释google规范


致谢:

https://google.github.io/styleguide/pyguide.html

https://zh-google-styleguide.readthedocs.io/en/latest/google-python-styleguide/python_language_rules/

http://legacy.python.org/dev/peps/pep-0008/

reStructuredText http://pengyao.org/rest-primer-chinese.html

Sphinx: http://my.phirobot.com/blog/2013-10-restructuretext_sphinx_resource.html

http://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html

https://www.cnblogs.com/makor/p/comment-in-open-source.html

https://www.cnblogs.com/jacob-tian/p/5976088.html

https://blog.csdn.net/ratsniper/article/details/78954852

http://www.doxygen.nl/manual/docblocks.html#pythonblocks

1前言

1.1 可读性

注释的目的之一是提升代码的可读性。

确保对模块, 函数, 方法和行内注释使用正确的风格。

Guido的一条重要的见解是代码阅读比写更加频繁。“Readability counts”。

PEP8 有时并不能完全对我们的开发规范和指导。看现在很多人的代码,发现 google coding style 的接受度更高。

本文使用了google规范,细节不足的部分用PEP 257补充。

1.2 生成文档

注释可以自动生成文档。

本文使用doxygen。

2风格说明

2.1Doxygen格式

Doxygen是一个程序的文档产生工具,可以将程序中的注释转换生成HTML格式的在线类浏览器,或离线的LATEX、RTF参考手册。

Doxygen支持python,包括docstring文档字符串。

官网示例如下:

For Python there is a standard way of documenting the code using so called documentation strings. Such strings are stored in doc and can be retrieved at runtime. Doxygen will extract such comments and assume they have to be represented in a preformatted way.

左边是源码注释,右面是转换后的HTML文件。

         

                          (a)源码注释                                                              (b)HTML文件。

源码文字:

"""@package docstring
Documentation for this module.
More details.
"""
def func():
    """Documentation for a function.
    More details.
    """
    pass
class PyClass:
    """Documentation for a class.
    More details.
    """
   
    def __init__(self):
        """The constructor."""
        self._memVar = 0;
   
    def PyMethod(self):
        """Documentation for a method."""
        pass
     
"""Documentation for a method."""

pass

 

2.2docstring文档字符串

文档字符串是Python中一种独一无二的的注释方式。适用于包, 文件/模块, 类和函数。

文档字符串是包, 模块, 类或函数里的第一个语句。

这些字符串可以通过对象的__doc__成员被自动提取, 并且被pydoc所用. (可以在你的模块上运行pydoc试一把, 看看它长什么样).

我们对文档字符串的惯例是使用三重双引号”“”( PEP-257 ). 一个文档字符串应该这样组织: 首先是一行以句号, 问号或惊叹号结尾的概述(或者该文档字符串单纯只有一行). 接着是一个空行. 接着是文档字符串剩下的部分, 它应该与文档字符串的第一行的第一个引号对齐.

下面依次描述。

 

3包(package)

3.1概念

为了组织好模块,将多个模块分为一个包。包是python模块文件所在的目录,且该目录下必须存在__init__.py文件。

常见的包结构如下:

package_a
├── __init__.py
├── module_a1.py
└── module_a2.py
package_b
├── __init__.py
├── module_b1.py
└── module_b2.py
main.py

3.2注释

注释写在__init__.py文件中。

注释内容可以归结为文件注释,具体参见文件章节。

 

4文件

4.1概念

文件即创建的一个脚本文件,里面定义了某些类、函数和变量。

4.2许可注释

每个文件根据开发需要考虑是否包含一个许可样板。

许可样板包括: Apache 2.0, BSD, LGPL, GPL等。

许可样板的含义参见:

https://www.cnblogs.com/jacob-tian/p/5976088.html

https://www.oschina.net/question/54100_9455

以Apache 2.0为例。https://blog.csdn.net/qi15211/article/details/84070709

如果遵循该协议,将Apache许可证应用于您的工作,请附上以下样板通知。

括号“[]”括起的字段将替换为您自己的标识信息。(不要包含括号!)文本应包含在文件格式的相应注释语法中。我们还建议将文件或类别名称和目的描述包含在与版权声明相同的“打印页面”中,以便在第三方档案中进行识别。

Copyright [yyyy] [name of copyright owner]
 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
 
    http://www.apache.org/licenses/LICENSE-2.0
 
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 

4.3本地注释

注释内容包括:

  1. 功能介绍
  2. 使用 Demo 示例以及参数/返回值等
  3. 作者、版权、license之类的说明

示例如下。

5模块

5.1概念

模块定义了某些函数和变量。你在需要这些功能时,从文件中导入这些模块,就可重用这些函数和变量。

5.2单文件单模块

当一个模块对应一个文件时,模块注释同文件注释。

5.3单文件多模块

模块注释一般就是解释该模块是干嘛用的,以及如何使用该模块等信息,同时,在构建工具之后就变成了文档的主要内容了。

注释内容包括:

  1. 功能介绍
  2. 使用 Demo 示例以及参数/返回值等

 

6类注释

6.1概念

类的概念在许多语言中出现,很容易理解。它将数据和操作进行封装,以便将来的复用。

6.2内容

类应该在其定义下有一个用于描述该类的文档字符串.

类的注释,除了必要的类说明和使用示例之外,你还需要对类的构造函数进行参数描述,因为 python 的构造函数是 __init__,而我们通常文档是直接看类的说明,所以这里写在类上很重要!

如果你的类有公共属性(Attributes), 那么文档中应该有一个属性(Attributes)段. 并且应该遵守和函数参数相同的格式.

注释内容包括:

  1. 功能介绍
  2. 使用示例、参数/返回值等
  3. 复杂的类需要注释实现思路

示例如下。

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

 

6函数和方法

6.1概念

下文所指的函数,包括函数, 方法, 以及生成器.

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

  1. 外部不可见
  2. 非常短小
  3. 简单明了

6.2内容

文档字符串应该包含函数做什么, 以及输入和输出的详细描述. 通常, 不应该描述”怎么做”, 除非是一些复杂的算法. 文档字符串应该提供足够的信息, 当别人编写代码调用该函数时, 他不需要看一行代码, 只要看文档字符串就可以了. 对于复杂的代码, 在代码旁边加注释会比使用文档字符串更有意义.

注释内容包括:

  1. 功能介绍
  2. 参数/返回值等
  3. 复杂的类标书实现思路

这里只有对函数的解释,注意事项还有返回值,除此之外,我们还经常用的有:

  • Args
  • Returns
  • Raises

关于函数的几个方面应该在特定的小节中进行描述记录, 这几个方面如下文所述. 每节应该以一个标题行开始. 标题行以冒号结尾. 除标题行外, 节的其他内容应被缩进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

 

7块注释和行注释

块与行

最需要写注释的是代码中那些技巧性的部分. 如果你在下次 代码审查 的时候必须解释一下, 那么你应该现在就给它写注释. 对于复杂的操作, 应该在其操作开始前写上若干行注释. 对于不是一目了然的代码, 应在其行尾添加注释.

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

对于行尾的注释,为了提高可读性, 注释应该至少离开代码2个空格.

另一方面, 绝不要描述代码. 假设阅读代码的人比你更懂Python, 他只是不知道你的代码要做什么.

# BAD COMMENT: Now go through the b array and make sure whenever i occurs
# the next element is i+1

代码间行尾注释风格

 

8特殊注释

比如#! /usr/bin/python  这句注释的意思就是告诉LINUX/UNIX去找到python的翻译器。

大部分文件都不需要这个,只在要求可直接执行的文件中添加。

关于中文编码:  # coding = utf-8    【注:这句代码必须放在第二行啊,而且多个空格都不行啊!】

9特定内容

9.1网址注释

Within comments, put long URLs on their own line if necessary.

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
版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/lzp_k2/article/details/89393782
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-02-13 15:37:45
  • 阅读 ( 1428 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢