Python风格规范
整理自Google开源项目指南
分号
- 不要在行尾加上分号,也不要用分号将两条命令分开;
行长度
- 每行长度不超过80个字符;
- 不要使用反斜杠连接行,可以使用圆括号来连接;
# True x = (‘This will build a very long long ‘ ‘long long long long long long string‘)
- URL可以单独放一行,不需要分割;
括号
- 除非是实现行连接,否则不要在返回语句或者条件语句中使用括号;
# wrong def foo(): if (True): print(‘True‘) return (True)
缩进
- 用4个空格来缩进代码,不要使用Tab。
空行
- 顶级定义(函数定义或者类定义)之间空两行,方法定义之间空一行;
空格
- 括号两边不要有空格;
- 不要在逗号,分号,冒号前面加空格,而是在后面加;
- 字典中冒号前面不用加空格,而是在后面加;
- 二元操作符两边都要加上一个空格,包括=、<、>、in、not in等等;
- 不要用空格垂直对齐多行间的标记;
# True foo = 1000 # comment long_name = 2 # comment that should not be aligned
注释
- 一个函数除非是非常短小或者简单明了,否则都应该有注释;
- 函数注释需要包括说明、参数、返回、异常;
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
- 类的注释包括说明,如果属性是公共属性,那么还需要包括属性;
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."""
- 块注释和行注释应该写代码做了什么(如果较复杂),而不是描述代码;
- 使用"""字符来标注;
类
- 如果一个类不继承自其它类,就显式的从object继承,不要什么都不写;
字符串
- 避免在循环中使用+来连接字符串,推荐使用数组的join;
- 在同一个文件中, 保持使用字符串引号的一致性;
TODO注释
- 为临时代码使用TODO注释, 它是一种短期解决方案;
- TODO注释应该在所有开头处包含”TODO”字符串,紧跟着是用括号括起来的你的名字,email地址或其它标识符,然后是一个可选的冒号,接着必须有一行注释,解释要做什么。
# True # TODO([email protected]): Use a "*" here for string repetition. # TODO(Zeke) Change this to use relations.
导入格式
- 每个导入应该独占一行;
# False import os, sys # True import os import sys
- 导入应该按照最通用到最不通用的顺序进行排序,首先是1. 标准库;2.第三方库;3. 模块库;
语句
- 除了exp if else,语句最好单独一行;
命名
- 使用单下划线开头表示模块变量或者函数是protected的;
- 使用双下划线开头表示实例变量或者方法是类内私有的;
- 类名应该使用大写字母开头的单词;
- 模块名和函数名和参数名应该使用小写加下划线的方式;
Main
- 为了避免倒入模块时被执行,需要加上mian的判断;
def main(): ... if __name__ == ‘__main__‘: main()
时间: 2024-12-15 20:57:07