Python常用PEP8编码规范和建议经验分享

缩进
每级缩进用4个空格。
括号中使用垂直隐式缩进或使用悬挂缩进。
example:
# (垂直隐式缩进)对准左括号
foo = long_function_name(var_one, var_two,
var_three, var_four)
# (悬挂缩进) 一般情况只需多一层缩进
foo = long_function_name(
var_one, var_two,
var_three, var_four)
# (悬挂缩进) 但下面情况, 需再加多一层缩进, 和后续的语句块区分开来
def long_function_name(
var_one, var_two, var_three,
var_four):
print(var_one)
# 右括号回退
my_list = [
1, 2, 3,
4, 5, 6,
]
result = some_function_that_takes_arguments(
'a', 'b', 'c',
'd', 'e', 'f',
)
错误示范:
# 不使用垂直对齐时,第一行不能有参数。
foo = long_function_name(var_one, var_two,
var_three, var_four)
# 参数的悬挂缩进和后续代码块缩进不能区别。
def long_function_name(
var_one, var_two, var_three,
var_four):
print(var_one)
# 右括号不回退,不推荐
my_list = [
1, 2, 3,
4, 5, 6,
]
result = some_function_that_takes_arguments(
'a', 'b', 'c',
'd', 'e', 'f',
)
最大行宽
每行最大行宽不超过 79 个字符
一般续行可使用反斜杠
括号内续行不需要使用反斜杠
example:
# 无括号续行, 利用反斜杠
with open('/path/to/some/file/you/want/to/read') as file_1, \
open('/path/to/some/file/being/written', 'w') as file_2:
file_2.write(file_1.read())
# 括号内续行, 尽量在运算符后再续行
class rectangle(blob):
def __init__(self, width, height,
color='black', emphasis=none, highlight=0):
if (width == 0 and height == 0 and
color == 'red' and emphasis == 'strong' or
highlight > 100):
raise valueerror(sorry, you lose)
if width == 0 and height == 0 and (color == 'red' or
emphasis is none):
raise valueerror(i don't think so -- values are %s, %s %
(width, height))
空行
两行空行用于分割顶层函数和类的定义
单个空行用于分割类定义中的方法
example:
# 类的方法定义用单个空行分割,两行空行分割顶层函数和类的定义。
class a(object):
def method1():
pass
def method2():
pass
def method3():
pass
模块导入
导入的每个模块应该单独成行
导入顺序如下: (各模块类型导入之间要有空行分割,各组里面的模块的顺序按模块首字母自上而下升序排列)
标准库
相关的第三方库
本地库
example:
# 按模块首字母排序导入, 依此递推
import active
import adidas
import create
错误示例:
# 一行导入多模块
import sys, os, knife
# 不按首字母导入
import create
import active
import beyond
字符串
单引号和双引号作用是一样的,但必须保证成对存在,不能夹杂使用.
(建议句子使用双引号, 单词使用单引号, 但不强制.)
example:
# 单引号和双引号效果一样
name = 'jmilkfan'
name = hey guys!
表达式和语句中的空格
括号里边避免空格
example:
spam(ham[1], {eggs: 2})
错误示例:
spam( ham[ 1 ], { eggs: 2 } )
逗号,冒号,分号之前避免空格
example:
if x == 4: print x, y; x, y = y, x
错误示例:
if x == 4 : print x , y ; x , y = y , x
函数调用的左括号之前不能有空格
example:
spam(1)
dct['key'] = lst[index]
错误示例:
spam (1)
dct ['key'] = lst [index]
赋值等操作符前后不能因为对齐而添加多个空格
example:
x = 1
y = 2
long_variable = 3
错误示例:
x = 1
y = 2
long_variable = 3
二元运算符两边放置一个空格
涉及 = 的复合操作符 ( += , -=等)
比较操作符 ( == , , != , , = , in , not in , is , is not )
逻辑操作符( and , or , not )
example:
a = b
a or b
# 括号内的操作符不需要空格
name = get_name(age, sex=none, city=beijing)
注释
注释块
注释块通常应用在代码前,并和代码有同样的缩进。每行以 ‘# ’ 开头, 而且#后面有单个空格。
example:
# have to define the param `args(list)`,
# otherwise will be capture the cli option when execute `python manage.py server`.
# oslo_config: (args if args is not none else sys.argv[1:])
conf(args=[], default_config_files=[config_file])
单行注释(应避免无谓的注释)
example:
x = x + 1 # compensate for border
文档字符串
example:
# 多行文档, 首行首字母大写,结尾的 应该单独成行
return a foobang
optional plotz says to frobnicate the bizbaz first.
# 单行的文档, 结尾的 在同一行。
return a foobang
命名规则
包和模块名:
包和模块名应该简短,全部用小写字母, 多字母之间可以使用单下划线连接。
类名:
遵循驼峰命名
class myclass(object):
pass
全局变量名:
全局变量名应尽量只在模块内部使用, 对可能使用语句 from modulename import variablename 而被导入的模块,应采用 __all__ 机制来防止全局变量被别的模块导入, 或者在全局变量名开头加一个前置下划线.
example:
name = 'name'
函数名
函数名应该为全部小写的凹驼峰规则。
example:
vcenter_connection = ''
常量名
常量全部使用大写字母的凹驼峰规则来表示, 通常在模块顶格定义
example:
max_overflow = ''
total = 1
方法名和实例变量
非公开方法和实例变量开头使用前置下划线
有时候可能会为了避免与子类命名冲突,采用两个前置下划线
需要注意的是: 若 class foo 的属性名为 __a, 该属性是不能以 foo.__a 的方式访问的(执著的用户还是可以通过foo._foo__a 来访问), 所以通常双前置下划线仅被用来避免与基类的属性发生命名冲突。
编程建议
none 的比较用 is 或 is not,而不要用 ==
用 is not 代替 not … is, 前者的可读性更好
example:
# yes
if foo is not none
# no
if not foo is none
使用函数定义关键字 def 代替 lambda 赋值给标识符, 这样更适合于回调和字符串表示
# yes
def f(x):
return 2*x
# no
f = lambda x: 2*x
异常类应该继承自exception,而不是 baseexception
python 2 中用raise valueerror('message') 代替 raise valueerror, 'message'
(考虑兼容python3和续行的方便性)
捕获异常时尽量指明具体异常, 尽量不用 except exception, 应该捕获 出了什么问题,而不是 问题发生
example:
# yes (捕获具体异常)
try:
import platform_specific_module
except importerror:
platform_specific_module = none
# no (不要全局捕获)
try:
import platform_specific_module
except:
platform_specific_module = none
try/except 子句中的代码要尽可能的少, 以免屏蔽掉其他的错误
example:
# yes
try:
value = collection[key]
except keyerror:
return key_not_found(key)
else:
return handle_value(value)
# no
try:
return handle_value(collection[key])
except keyerror:
# 可能会捕捉到 handle_value()中的 keyerror, 而不是 collection 的
return key_not_found(key)
函数或者方法在没有返回值时要明确返回 none
# yes
def foo():
return none
# no
def foo():
return
使用字符串方法而不是 string 模块
python 2.0 以后字符串方法总是更快,而且与 unicode 字符串使用了相同的 api
使用使用 .startswith() 和 .endswith() 代替字符串切片来检查前缀和后缀
startswith() 和 endswith 更简洁,利于减少错误
example:
# yes
if foo.startswith('bar'):
# no
if foo[:3] == 'bar':
使用 isinstance() 代替对象类型的比较
example:
# yes
if isinstance(obj, int):
# no
if type(obj) is type(1):
空序列类型对象的 bool 为 false:
# yes
if not seq:
pass
if seq:
pass
# no
if len(seq):
pass
if not len(seq):
pass
不要用 == 进行 bool 比较
# yes
if greeting:
pass
# no
if greeting == true
pass
if greeting is true: # worse
pass

一个有效、可靠的数据通信网络必须满足哪些标准?
IIC-China 2010春季展前报道四:汽车电子
差分信号共模电压ADC输入电路设计
如何用BMIC解决由多个电池单元串联而成电池串的问题
单相变压器的参数测定实验
Python常用PEP8编码规范和建议经验分享
ios10.3正式版增加了哪些功能?ios10.3那些你从没注意到的功能
「上海晶珩EDATEC」「工业树莓派」树莓派外置存储!
基于PID算法的铅酸蓄电池智能充电设计
日本触媒扩大锂电池用电解质IONEL(LiFSI)的制造设施
2020年底Microsoft Edge、IE11都将停止对Adobe Flash Player的支持
氮氧化物在线监测仪的应用及注意事项
e 络盟提供全面的物联网开发工具,推出新型人工智能和安全解决方案
小米618狂赚52亿,拿下多项手机销量第一
环形超声波马达的结构组成及其工作原理的介绍
智能商务投影机助力开启会议办公的新时代
2020中国计算机教育大会于厦门国际会议中心举办
三星Galaxy S21和iPhone 12有什么样的差异
河套IT TALK——TALK42:(原创)视频制作的人工智能时代要到来了,你准备好了吗?
滨海城市海洋水质在线监测