缩进
用4个空格来缩进代码
分号
不要在行尾加分号, 也不要用分号将两条命令放在同一行。
行长度
每行不超过80个字符
以下情况除外:
l 长的导入模块语句
l 注释里的URL
不要使用反斜杠连接行。
Python会将 圆括号, 中括号和花括号中的行隐式的连接起来 , 你可以利用这个特点. 如果需要, 你可以在表达式外围增加一对额外的圆括号。
命名规范
避免的情况:
- 变量名尽量有意义,长度在一个字符以上(除了计数器和迭代器)
- 包,模块名中不要出现连字符(-)
- 不要将变量名以双划线开头并结尾(如__init__为python保留特殊变量)
命名约定
- 用单下划线(_)开头表示模块变量或函数是protected的(使用import * from时不会包含).
- 用双下划线(__)开头的实例变量或方法表示类内私有.
- 将相关的类和顶级函数放在同一个模块里. 不像Java, 没必要限制一个类一个模块.
- 对类名使用大写字母开头的单词(如CapWords, 即Pascal风格), 但是模块名应该用小写加下划线的方式(如lower_with_under.py). 尽管已经有很多现存的模块使用类似于CapWords.py这样的命名, 但现在已经不鼓励这样做, 因为如果模块名碰巧和类名一致, 这会让人困扰.
PEP8 命名:
- 函数、变量及属性应用小写字母拼写,各单词之间以下划线相连,例如,lowercase_underscore
- 受保护的实例属性,应该以单个下划线开头,例如,_leading_underscore
- 私有的实例属性,应该以两个下划线开头,例如,__double_leading_underscore
- 类与异常,应该以每个单词首字母均大写来命名,例如,CapitalizedWord
- 模块级别的常量,应该全部采用大写字母来拼写,各单词之间以下划线相连,例如,ALL_CAPS
- 类中的实例方法,应该把首个参数命名为self,以表示该对象自身
- 类方法的首个参数,应该命名为cls,以表示该类自身
Python之父Guido推荐的规范
(所谓"内部(Internal)"表示仅模块内可用, 或者, 在类内是保护或私有的
Type |
Public |
Internal |
Modules |
lower_with_under |
_lower_with_under |
Packages |
lower_with_under |
|
Classes |
CapWords |
_CapWords |
Exceptions |
CapWords |
|
Functions |
lower_with_under() |
_lower_with_under() |
Global/Class Constants |
CAPS_WITH_UNDER |
_CAPS_WITH_UNDER |
Global/Class Variables |
lower_with_under |
_lower_with_under |
Instance Variables |
lower_with_under |
_lower_with_under (protected) or __lower_with_under (private) |
Method Names |
lower_with_under() |
_lower_with_under() (protected) or __lower_with_under() (private) |
Function/Method Parameters |
lower_with_under |
|
Local Variables |
lower_with_under |
注释
确保对模块, 函数, 方法和行内注释使用正确的风格
文档字符串
Python有一种独一无二的的注释方式: 使用文档字符串. 文档字符串是包, 模块, 类或函数里的第一个语句. 这些字符串可以通过对象的__doc__成员被自动提取, 并且被pydoc所用. (你可以在你的模块上运行pydoc试一把, 看看它长什么样). 我们对文档字符串的惯例是使用三重双引号"""( PEP-257 ). 一个文档字符串应该这样组织: 首先是一行以句号, 问号或惊叹号结尾的概述(或者该文档字符串单纯只有一行). 接着是一个空行. 接着是文档字符串剩下的部分, 它应该与文档字符串的第一行的第一个引号对齐. 下面有更多文档字符串的格式化规范.
函数和方法
下文所指的函数,包括函数, 方法, 以及生成器.
一个函数必须要有文档字符串, 除非它满足以下条件:
l 外部不可见
l 非常短小
l 简单明了
文档字符串:
应该包含函数做什么, 以及输入和输出的详细描述. 通常, 不应该描述"怎么做", 除非是一些复杂的算法. 文档字符串应该提供足够的信息, 当别人编写代码调用该函数时, 他不需要看一行代码, 只要看文档字符串就可以了. 对于复杂的代码, 在代码旁边加注释会比使用文档字符串更有意义.
关于函数的几个方面应该在特定的小节中进行描述记录, 这几个方面如下文所述. 每节应该以一个标题行开始. 标题行以冒号结尾. 除标题行外, 节的其他内容应被缩进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
类
类应该在其定义下有一个用于描述该类的文档字符串. 如果你的类有公共属性(Attributes), 那么文档中应该有一个属性(Attributes)段. 并且应该遵守和函数参数相同的格式.
示例:
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."""
块注释和行注释
最需要写注释的是代码中那些技巧性的部分. 如果你在下次 代码审查 的时候必须解释一下, 那么你应该现在就给它写注释. 对于复杂的操作, 应该在其操作开始前写上若干行注释. 对于不是一目了然的代码, 应在其行尾添加注释.
# 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 a power of 2
为了提高可读性, 注释应该至少离开代码2个空格.
模块导入
Import 语句应该按顺序划分成三个部分,分别表示标准库模块,第三方模块及自用模块,在每个部分中,各import语句应该按模块的字母顺序来排列
其他建议
类
如果一个类不继承自其它类, 就显式的从object继承. 嵌套类也一样
继承自 object 是为了使属性(properties)正常工作, 并且这样可以保护你的代码, 使其不受Python 3000的一个特殊的潜在不兼容性影响. 这样做也定义了一些特殊的方法, 这些方法实现了对象的默认语义, 包括 __new__, __init__, __delattr__, __getattribute__, __setattr__, __hash__, __repr__, and __str__
字符串
避免在大循环中用+和+=拼接字符串,这样做会创建不必要的临时对象,且会使得代码运行时间以二次方增长,作为替代方案, 你可以将每个子串加入列表, 然后在循环结束后用 .join 连接列表.
使用with语句
为了确保文件句柄能在不用时关闭,请使用with...as语句
with open("hello.txt") as hello_file:
for line in hello_file:
print line