

给你的代码跑个分?pylint使用教程
source link: https://jiajunhuang.com/articles/2020_03_12-pylint.md.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

给你的代码跑个分?pylint使用教程
之前我一直使用 flake8
来检查Python项目中的代码规范,工作良好,除了一个问题,由于Python是动态语言,编译器只能做最基本
最简单的错误检查,这也就意味着,很多错误,如果肉眼看不出来,那就得等执行报错了才会被发现。
因此有必要使用 pylint 这种代码检查器来减少出错的概率。
各Linux发行版可以直接安装:
$ sudo apt install pylint
不过如果是使用了虚拟环境例如 pyenv
, venv
, virtualenv
等,还是建议在当前环境中直接安装:
$ pip install pylint
pylint
默认的输出有一些可能不适用于我们的项目,因此要有一个配置文件来进行配置,编辑 ~/.pylintrc
:
[FORMAT]
max-line-length=120
[MESSAGES CONTROL]
disable=C0114,C0116,C0103,W0703,C0115,R0201,R0914,R0903,R0913,R0801
比如上面的配置文件,就是说代码超过120个字符才会报代码过长,然后下面 MESSAGES CONTROL
中禁用的错误/警告类型就不会报错。
而这些错误警告码呢,就是自己来定制的,我是从 pylint <项目文件夹或代码文件>
的结果中抄出来的,比如:
hello = 1
在没有配置文件的情况下运行一下:
$ pylint hello.py
************* Module hello
hello.py:2:5: C0326: Exactly one space required around assignment
world=2
^ (bad-whitespace)
hello.py:1:0: C0114: Missing module docstring (missing-module-docstring)
hello.py:1:0: C0103: Constant name "hello" doesn't conform to UPPER_CASE naming style (invalid-name)
hello.py:2:0: C0103: Constant name "world" doesn't conform to UPPER_CASE naming style (invalid-name)
----------------------------------------------------------------------
Your code has been rated at -10.00/10 (previous run: -10.00/10, +0.00)
有一些提示就不是特别适用,比如 C0114: Missing module docstring (missing-module-docstring)
,
于是把 C0114
加到 disable=
后面,再次运行:
$ pylint hello.py
************* Module hello
hello.py:2:5: C0326: Exactly one space required around assignment
world=2
^ (bad-whitespace)
------------------------------------------------------------------
Your code has been rated at 5.00/10 (previous run: 5.00/10, +0.00)
不过我们不能每次都依靠跑一遍命令来检查错误,这种模式比较适用于CI,我们希望在编辑代码的时候就看到提示,不过这 一点也不难,比如vim,我使用
ale
这个插件,他默认如果检测到pylint
就会使用pylint
来检查
这个时候就好很多。注意 pylint
的输出里,最后会给你的代码评一个分,比如我维护的一个系统,在改之前是9.5分,
照着pylint给出的建议,改成了10分,你的呢?

关注公众号,获得及时更新
Ubuntu 18.04 dhcp更换新IP
Python中的新式类(new style class)和老式类(old style class)
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK