python代码规范(Google)
格式规范
- 不要加分号
- 每行不超过80字符
- 不要使用反斜杠连接行
- 用4个空格来缩进代码
- 顶级定义之间空两行,方法定义之间空一行。
- 空格
- 括号内不要空格
- 不要在逗号,分号,冒号前面加空格,但应该在后面加(除了行尾)
- 参数列表,索引或切片的左括号前不应加空格
- 在二元操作符两边都加上一个空格
- 当’='用于指示关键字参数或默认参数值时,不要在其两侧使用空格,例如
def complex(a=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或其他类似文件的对象在没有必要的情况下打开,会有很多副作用,例如:
- 可能会消耗有限的系统资源,如文件描述符。如果这些资源在使用后没有即使归还系统,那么用于处理这些对象的代码会将资源消耗殆尽
- 持有文件将会组织对于文件的其他诸如移动、删除之类的操作。
- 仅仅从逻辑上关闭文件和sockets,那么它们仍然可能会被其共享的程序在无意中进行和读或者写操作。
- 推荐使用‘with’管理文件:
with open('q.txt') as f:
for line in f:
print(line)
f.closed()
- 对于不支持使用“with"语句的类似文件对象,使用contextlib.closing():
import contextlib
with contextlib.closing(urllib.urlopen("http://www.python.org/")) as front_page:
for line in front_page:
print line
命名规范
- 应该避免的名称。
- 单字符名称
- 模块名中不能出现连字符
- 不能编写双下划线开头并结尾的名称
- 命名约定
- 用单下划线(_)开头表示模块变量或函数是protected
- 用双下划线(_)开头表示模块变量或函数是private
- 将相关的类和顶级函数放在同一个模块里
- 对类名使用大驼峰命名法,模块名用小写加下划线的命名方法。
常量声明使用大写字符,并用下划线分隔,例如NAMES_LIKE_THIS
注释
- 文件注释
顶层开头注释用于告诉不熟悉代码的读者这个文件包含哪些东西,应该提供文件的大体内容,它的作者,依赖关系和兼容性信息。如下:
/**
* 文件描述,他的使用和必要信息
* 存在的依赖
* 作者
- 类注释
类注释描述类的功能和用法,也需要说明说明构造器参数。
如果一个类不继承自其它类, 就显式的从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_spam
self.eggs = 0
def public_method(self):
"""Performs operation blah."""
- 方法和函数的注释
提供参数的说明,使用完整的句子,并用第三人称来书写说明。
def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
"""方法内容
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.
参数:
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
- 属性注释
提供参数的说明,使用完整的句子,并用第三人称来书写说明
/**
* 参数描述
* @type {string} 值描述
- 类型转换注释
添加类型标记注释来明确,必须要在表达式和类型注释外面包裹括号。
/** */ (x)
- 将长的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
- 块注释和行注释
最需要写注释的是代码中那些技巧性的部分. 如果你在下次 代码审查 的时候必须解释一下, 那么你应该现在就给它写注释. 对于复杂的操作, 应该在其操作开始前写上若干行注释. 对于不是一目了然的代码, 应在其行尾添加注释.
# 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.
- TODO注释
为临时代码使用TODO注释,它是一种短期解决方案。
TODO注释应该在所有注释开头处包含"TODO"字符串,然后括号自己的邮箱或者名字,并说明字符内容。具体示例如下:
# TODO(kl@gmail.com): Use a "*" here for string repetition.
# TODO(Zeke) Change this to use relations.