编码工作之python编程规范总结-Google版
创始人
2024-05-25 04:47:46
0

python代码规范(Google)

格式规范

  1. 不要加分号
  2. 每行不超过80字符
  3. 不要使用反斜杠连接行
  4. 用4个空格来缩进代码
  5. 顶级定义之间空两行,方法定义之间空一行。
  6. 空格
  • 括号内不要空格
  • 不要在逗号,分号,冒号前面加空格,但应该在后面加(除了行尾)
  1. 参数列表,索引或切片的左括号前不应加空格
  2. 在二元操作符两边都加上一个空格
  3. 当’='用于指示关键字参数或默认参数值时,不要在其两侧使用空格,例如def complex(a=1)是对的。
  4. 不要用空格来垂直对齐多行间的标记。
  5. 导入格式

每个导入应该独占一行
导入应该在文件顶部。导入顺序应按照通用到不通用顺序,标准库大于第三方库大于程序库

  1. 每个语句应该独占一行。
    如果测试结果与测试语句在一行不大于80字符,同样可以放在同一行。如果是if语句,只有没有else时才能这样做;try/except也不能这样排列。例如:
Yes:if foo: bar(foo)
No:if foo: bar(foo)else:   baz(foo)try:               bar(foo)except ValueError: baz(foo)try:bar(foo)except ValueError: baz(foo)

文件和sockets

在文件和sockets结束时, 显式的关闭它.
除文件按外,sockets或其他类似文件的对象在没有必要的情况下打开,会有很多副作用,例如:

  1. 可能会消耗有限的系统资源,如文件描述符。如果这些资源在使用后没有即使归还系统,那么用于处理这些对象的代码会将资源消耗殆尽
  2. 持有文件将会组织对于文件的其他诸如移动、删除之类的操作。
  3. 仅仅从逻辑上关闭文件和sockets,那么它们仍然可能会被其共享的程序在无意中进行和读或者写操作。
  • 推荐使用‘with’管理文件:
with open('q.txt') as f:for line in f:print(line)
f.closed()
  • 对于不支持使用“with"语句的类似文件对象,使用contextlib.closing():
import contextlibwith contextlib.closing(urllib.urlopen("http://www.python.org/")) as front_page:for line in front_page:print line

命名规范

  1. 应该避免的名称。
  • 单字符名称
  • 模块名中不能出现连字符
  • 不能编写双下划线开头并结尾的名称
  1. 命名约定
  • 用单下划线(_)开头表示模块变量或函数是protected
  • 用双下划线(_)开头表示模块变量或函数是private
  • 将相关的类和顶级函数放在同一个模块里
  • 对类名使用大驼峰命名法,模块名用小写加下划线的命名方法。

常量声明使用大写字符,并用下划线分隔,例如NAMES_LIKE_THIS

注释

  1. 文件注释
    顶层开头注释用于告诉不熟悉代码的读者这个文件包含哪些东西,应该提供文件的大体内容,它的作者,依赖关系和兼容性信息。如下:

/**
* 文件描述,他的使用和必要信息
* 存在的依赖
* 作者
  1. 类注释
    类注释描述类的功能和用法,也需要说明说明构造器参数。
    如果一个类不继承自其它类, 就显式的从object继承. 嵌套类也一样。示例如下:
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_spamself.eggs = 0def public_method(self):"""Performs operation blah."""
  1. 方法和函数的注释
    提供参数的说明,使用完整的句子,并用第三人称来书写说明。
def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):"""方法内容Retrieves rows pertaining to the given keys from the Table instancerepresented by big_table.  Silly things may happen ifother_silly_variable is not None.参数:big_table: An open Bigtable Table instance.keys: A sequence of strings representing the key of each table rowto fetch.other_silly_variable: Another optional variable, that has a muchlonger name than the other args, and which does nothing.Returns:A dict mapping keys to the corresponding table row datafetched. Each row is represented as a tuple of strings. Forexample:{'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
  1. 属性注释
    提供参数的说明,使用完整的句子,并用第三人称来书写说明
/**
* 参数描述
* @type {string} 值描述
  1. 类型转换注释
    添加类型标记注释来明确,必须要在表达式和类型注释外面包裹括号。
/**  */ (x)
  1. 将长的URL放在一行上
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
  1. 块注释和行注释

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

# 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.
  1. TODO注释
    为临时代码使用TODO注释,它是一种短期解决方案。
    TODO注释应该在所有注释开头处包含"TODO"字符串,然后括号自己的邮箱或者名字,并说明字符内容。具体示例如下:
# TODO(kl@gmail.com): Use a "*" here for string repetition.
# TODO(Zeke) Change this to use relations.

相关内容

热门资讯

监控摄像头接入GB28181平... 流程简介将监控摄像头的视频在网站和APP中直播,要解决的几个问题是:1&...
Windows10添加群晖磁盘... 在使用群晖NAS时,我们需要通过本地映射的方式把NAS映射成本地的一块磁盘使用。 通过...
protocol buffer... 目录 目录 什么是protocol buffer 1.protobuf 1.1安装  1.2使用...
在Word、WPS中插入AxM... 引言 我最近需要写一些文章,在排版时发现AxMath插入的公式竟然会导致行间距异常&#...
【PdgCntEditor】解... 一、问题背景 大部分的图书对应的PDF,目录中的页码并非PDF中直接索引的页码...
Fluent中创建监测点 1 概述某些仿真问题,需要创建监测点,用于获取空间定点的数据࿰...
educoder数据结构与算法...                                                   ...
MySQL下载和安装(Wind... 前言:刚换了一台电脑,里面所有东西都需要重新配置,习惯了所...
修复 爱普生 EPSON L4... L4151 L4153 L4156 L4158 L4163 L4165 L4166 L4168 L4...
MFC文件操作  MFC提供了一个文件操作的基类CFile,这个类提供了一个没有缓存的二进制格式的磁盘...