Python代码的PEP8 检查

        Python社区提出了编写Python代码的PEP8(https://www.python.org/dev/peps/pep-0008/)标准。基本上,归纳规则为:

1、每个缩进层级使用4个空格

2、每行最多79个字符

3、顶层函数或类的定义之间空两行(特别容易漏,漏的话,是报E302 expected 2 blank lines, found 1)

4、采用ASCII或者UTF-8编码文件

5、每条import导入一个模块,导入放在代码顶端,导入顺序是先标准库,第三方库,本地库

6、 小括号,大括号,中括号之间的逗号没有额外的空格

7、类命名采用骆驼命名法,CamelCase;函数用小写字符

8、函数命名使用小写字符,例如xxx_xxx_xxx;用下划线开头定义私有的属性或方法,如_xxx

这些规范其实是容易遵守的,也很合理,但是有时会疏忽,这时可以尝试利用工具达到事半功倍的效果。pep8就是用来解决规范的问题的,自动检查python文件是否符合PEP8规范。

首先安装pep8; pip install -U pep8 (pip安装:http://www.linuxde.net/2014/05/15576.html);OK,开始验证代码了

测试代码:const.py  (91条建议里的一个代码,也存在编码规范问题)

class _const:
    class ConstError(TypeError): pass
    class ConstCaseError(ConstError): pass
 
    def __setattr__(self, name, value):
        if self.__dict__.has_key(name):
            raise self.ConstError, "Can't change const.%s" % name
        if not name.isupper():
            raise self.ConstCaseError, "const name %s is not all upper" % name
        self.__dict__[name] = value
 
import sys
sys.modules[__name__] = _const()

# pep8 const.py
const.py:2:32: E701 multiple statements on one line (colon)
const.py:3:5: E301 expected 1 blank line, found 0
const.py:3:37: E701 multiple statements on one line (colon)
const.py:6:25: W601 .has_key() is deprecated, use 'in'
const.py:12:1: E402 module level import not at top of file
 

猜你喜欢

转载自blog.csdn.net/triumph12345/article/details/85728258