Python编码规范踩过的坑

Python编码规范踩过的坑,第1张

Python编码规范踩过的坑

Python编码规范踩过的坑
  • 1.try.....except.....
  • 2.whitespace
  • 3.indent
  • 4. 与 ()
  • 5. and与or

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'
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')

持续更新中。。。。。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5680547.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存