Python编码规范踩过的坑
PEP8编码规范
1.try…except…
E722 do not use bare ‘except’, specify exception instead
对于except,按照规范最好不要使用bare except, 而是使用具体的except
例如:
// correct
try:
user = User.objects.get(pk=user_id)
user.send_mail('Hello world')
except User.DoesNotExist:
logger.error('The user does not exist with that ID')
//No specification
try:
user = User.objects.get(pk=user_id)
user.send_mail('Hello world')
except:
logger.error('The user does not exist with that ID')
2.whitespace
E226 missing whitespace around arithmetic operator
当使用算术运算符或者分隔符后要注意符号周围的空格。例如:
// correct
list = [0, 1, 2, 3, 4]
for i in range(len(list) / 2):
print(list)
//No specification
list = [0, 1, 2, 3, 4]
for i in range(len(list)/2):
print(list)
3.indent
E125
E125 continuation line with same indent as next logical line
有时候为了追求上下行对齐,在换行后,延续行与下一个逻辑行具有相同的缩进时会引发该错误。
// correct
if user is None and user.admin or \
user.name == 'Blue':
ohter = 'hah'
//No specification
if user is None and user.admin or \
user.name == 'Blue':
ohter = 'hah'
E131
E131 continuation line unaligned for hanging indent
// correct
if user is None and user.admin or \
user.name == 'Blue' or \
user.age == '17':
ohter = 'hah'
//No specification
if user is None and user.admin or \
user.name == 'Blue' or \
user.age == '17':
ohter = 'hah'
E111&E117
E111 indentation is not a multiple of four
E117 over-indented
// correct
def testRun(self):
pass
//No specification
def testRun(self):
pass //缩进问题,不是四的倍数将会报E111的error,同时由于缩进超过4,报E117的error.
E114
E114 indentation is not a multiple of four (comment)
该error同E111,不同的时针对的是comment
// correct
def testRun(self):
# comment
//No specification
def testRun(self):
# comment
4.\ 与 ()
在python中如果一句写不下可以使用换行符或者()但是不能两个一起用
// correct
if user is None and user.admin or \
user.name == 'Blue':
ohter = 'hah'
//No specification
if (user is None and user.admin or \
user.name == 'Blue'):
ohter = 'hah'
5. and与or
and与or一般常用与条件判断中,如果想要达到预期效果需要小心使用
// print的结果为yes
a = 3
b = 2
if a == 3 or a == 2 and b == 1:
print('yes')
else:
print('no')
//print的结果为no
a = 3
b = 2
if (a == 3 or a == 2) and b == 1:
print('yes')
else:
print('no')
6. list 相关
6.1 list元素一行写不下时
// correct
list = [
1,2,3,
4,5,6
]
//No specification
//将会引发The backslash is redundant between brackets (E502)错误
list = [1,2,3,\
4,5,6]
6.2 list存在子列表时,进行去[]合并
// 第一种方法
list = [
[1,2,3],
[4,5,6]
]
list_test = []
for i in range(0, 2):
list_test.extend(list[i])
print(list_test) //[1,2,3,4,5,6]
//第二种方法
list = [
[1,2,3],
[4,5,6]
]
list_test = []
list_test = reduce(lambda x, y: x.extend(y) or x, list)
print(list_test)//[1,2,3,4,5,6]
7. PEP8对于单行编码数量要求
PEP8中对于python单行编码要求不能超过120个characters.
否则会报错(x为实际单行编码数量):
E501 line too long (x > 120 characters)
8. bank line
E301 expected 1 blank line, found 0
一个函数的结束和一个函数的开始应该有一个空白行,举例如下:
// correct
def testRun(self):
pass
def testInit(self):
pass
//No specification
def testRun(self):
pass
def testInit(self):
pass
持续更新中。。。。。