PEP是Python Enhancement Proposal的缩写,通常翻译为“Python增强提案”。每个PEP都是一份为Python社区提供的指导Python往更好的方向发展的技术文档,其中的第8号增强提案(PEP 8)是针对Python语言编订的代码风格指南。可以从Python官方网站找到该文档:
PEP 8 - Style Guide for Python Code
前几天认真读了一下 Python PEP 8 编码规范,对比自己编写代码常常疏忽的地方,做笔记如下,后续需特别注意这几点。
每行不超过80字符,不要用\ 换行,用() [] {} 隐式换行
文本字符串太长也可分成几段,然后用圆括号实现换行和隐式连接
对URL不要换行
在代码中使用括号宁缺毋滥
不要用空格来对齐多行间的标记,会成为负担(适用 : # = 等)
二元操作符两边加空格,算数操作符随意但要两边一致,在“=”用于关键字参数或默认参数时,不要在其两侧使用空格
顶级定义(如函数或类)空两行,类定义与第一个方法间空一行,其它觉得合适就空一行
每个导入应该独占一行, 不建议写到一行里。
# Correct: import os import sys # Wrong: import os, sys导入应位于文件顶部,在模块注释和文档字符串之后,在模块的全局变量与常量之前。导入应按以下顺序分组,且每组导入之间加入一个空行:
标准库的导入
相关第三方库的导入
本地应用/库的特定导入
避免通配符的导入,因为这样做就不知道命名空间中存在哪些名字,会使得后续有很多混淆。
# Wrong: from xxxmodule import *使用有意义的英文单词或词组,不建议使用拼音
用下划线表示变量或函数是内部或私有,即protected的
类名使用大写字母开头单词,但模块名应该小写加下划线
中间不要使用连字符(-),除了计数器之外,不要使用单字符命名
各种类型的命名规范,如:module_name, package_name, ClassName, method_name, ExceptionName, function_name, GLOBAL_VAR_NAME, instance_var_name, function_parameter_name, local_var_name。
具体参见下表:
TypepublicInernalModuleslower_with_under_lower_with_underPackageslower_with_underClassesCapWords_CapWordsExceptionsCapWordsFunctionslower_with_under()_lower_with_under()Global/Class ConstansCAPS_WITH_UNDERGlobal/Class Variableslower_with_under_lower_with_underInstance Variableslower_with_under_lower_with_under(protected)or __lower_with_underMethod Nameslower_with_under()_lower_with_under(protected)or __lower_with_underFunction/Method Parameterslower_with_underLocal Variableslower_with_under文档字符串是包/模块/类/函数的第一个语句,惯例用三重双引号(”””)
文档字符串通常为概述1行+空行+详细描述,也可只有1行概述
函数或方法除非很短、简单,外部不可见,才可不写文档字符串
为临时代码使用TODO注释,如下:
# TODO(name@email.com): Change this to use relations.每个文件应该包含一个许可样板,如:Apache 2.0, LGPL, GPL
函数的参数、返回值或异常(以及类的公共属性)都需要详细描述。举例如下:
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以上,很多都是容易疏忽的内容,记录备查。