你需要知道的Python代码规范性检查(pylint和flake8)

时间:2022-07-28
本文章向大家介绍你需要知道的Python代码规范性检查(pylint和flake8),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

关于Python代码规范,之前写过一篇相关的文章你熟悉Python的代码规范吗?如何一键实现代码排版,大家可以先看下。

Python代码规范要遵从PEP规范,Python官方的PEP8指南:https://www.python.org/dev/peps/pep-0008/,可以回复“编码规范”获取最新pep8规范中文版。

我们知道规范的内容很多,不可能都记住,每次写完代码,也不可能一条条去检查,有没有什么好用的检查工具呢。

今天,就给大家介绍python中有两个非常好用的代码检查工具-pylintflake8

Pylint

Pylint是一个Python代码分析工具,它分析 Python 代码中的错误,查找不符合代码风格标准(Pylint 默认使用的代码风格是 PEP 8)和有潜在问题的代码。

安装

pip install pylint

安装完成后,可以查看pylint的版本信息

#新建一个pycheck.py文件
def print_num1():
    print("1")
def PrintNum2():
    print("2")
print_num1()
PrintNum2()

使用

pylint + 目标项目或者文件

pylint pychek.py

输出:

************* Module pycheck
pycheck.py:1:0: C0114: Missing module docstring (missing-module-docstring)
pycheck.py:1:0: C0116: Missing function or method docstring (missing-function-docstring)
pycheck.py:3:0: C0103: Function name "PrintNum2" doesn't conform to snake_case naming style (invalid-name)
pycheck.py:3:0: C0116: Missing function or method docstring (missing-function-docstring)

------------------------------------------------------------------
Your code has been rated at 3.33/10 (previous run: 3.33/10, +0.00)

使用pylint有如下几种提示级别Error(错误)、Warning(警告)、Refactor(重构)、Convention(规范)。

输出的结果包括:与规范冲突的位置(行列)、违反的规范编号以及具体的内容提示,还有一个有趣的地方,就是会给检查项目打分,满分10分,大家可以试试自己的项目,看看编码规范评分是多少。

从检查信息可以看到,上述代码缺少模块注释(Missing module docstring)以及函数注释(Missing function docstring),函数名不符合蛇形命名规范(全由小写字母和下划线组成,在两个单词之间用下滑线连接)。

修改后

"""打印模块"""
def print_num1():
    """function1  输出数字1"""
    print("1")


def print_num2():
    """function2  输出数字2"""
    print("2")


print_num1()
print_num2()

执行:pylint pychek.py

输出:
-------------------------------------------------------------------

Your code has been rated at 10.00/10 (previous run: 8.33/10, +1.67)

在pycharm中配置pylint

pylint也可以关联到pycharm中,不用每次手动执行命令,配置好后,直接点击按钮执行即可。

name:pylint
Program: pylint.exe所在地址
Arguments:$FilePath$

在需要检查的项目中,右键选择pylint即可。

Flake8

Flake8 是由Python官方发布的一款辅助检测Python代码是否规范的工具,相对于目前热度比较高的Pylint来说,Flake8检查规则灵活,支持集成额外插件,扩展性强。可以编写程序实现代码规范性检测。

flake安装

pip install flake8

使用与pylint类似:

flake8 pycheck.py

输出:
D:testwebpra>flake8 D:testwebprapycheck.py
D:testwebprapycheck.py:3:1: E302 expected 2 blank lines, found 0
D:testwebprapycheck.py:5:1: E305 expected 2 blank lines after class or function definition, found 0

在pycharm中配置flake8

配置与pylint类似

name:Flake8(随便写一个)
Program: `$PyInterpreterDirectory$/python`
Arguments: -m flake8 --max-line-length=130 --exclude venv,migrations $ProjectFileDir$ (可以根据自己的需求进行配置)
Working directory: `$ProjectFileDir$`

在需要检查的项目中,右键选择Flake8即可。

关于pylint和flake8,这里只介绍了最基本的用法,更多检查的策略和配置,大家可以查看官网的介绍。

https://pylint.readthedocs.io/en/latest/

https://flake8.pycqa.org/en/latest/