Python编码规范踩过的坑
程序员文章站
2022-04-11 17:05:52
...
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 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 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'
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'
持续更新中。。。。。
上一篇: python编码规范(二)--空格的使用