Ourren

关注技术,记录生活.

Python代码规范入门

| 留言

虽然接触Python已经有好几年了,同时前前后后也开发过很多小工具或者系统,但是一直觉得代码不是很规范,最近抽空了解了这方面的资料,现归纳如下,也方便pythoner学习,文章首先介绍Python代码规范的程序,然后分享在Pycharm中嵌入Pylint程序来实现快速检测代码质量。

Google开放的各类语言代码规范中就有就有「Python风格规范」, 里面对语言规范和风格规范进行了详细的描述,不失为提升自己代码规范的入门资料。但是让我阅读「编写高质量代码 改善Python程序的91个建议」此书时才发现原来Google这种代码规范属于「PEP8」规范。同样,PEP8也不是唯一的风格检测程序,类似的应用还有Pychecker、Pylint、Pyflakes等。其中,Pychecker是Google Python Style Guide推荐的工具;Pylint因可以非常方便地通过编辑配置文件实现公司或团队的风格检测而受到许多人的青睐;Pyflakes则因为易于集成到vim中,所以使用的人也非常多。这样看我们只需要选择一个适合自己的代码规范即可,而如上所述,Pylint高可配置性,高可定制性,并且可以很容易写小插件来添加功能。因此,我最终选择了Pylint来实现代码规范检测。

Pycahrm集成Pylint

Pycharm是我目前最喜欢的Python IDE「请不要把Sublime拿来对比,当你写大项目的时候你就知道区别了」。当我搜索如何把Pylint集成到Pycharm的时候发现其实资料很少「参考4,5」,按着步骤做还有些问题,遂修正如下:

安装pylint

sudo pip install pylint

依次打开如下菜单:

Open “Settings > Tools > External Tools” and press the “+” button.

step1

设置相关参数,参数和工作目录请使用宏,点击即可选择:

step1

添加此插件到工具栏:在工具栏点右键—“Customize Menus and Toolbars”—“Main Toolbar”—“Help Topics”—-“Add after”—“External Tools”—“Pylint”, 然后就搞定了。

测试实践

代码写好了之后按一下这个按钮即可对改代码进行规范性检测,同时测试报告会给出你不符合规格的行数和问题,测试效果可以参照「6」进行测试,例如测试下面的代码:

 Customize Menus and Toolbars#coding:utf-8
'''
    a test function module
'''
import urllib
import time

def fetch(url):
    '''
        fetch url
    '''
    content = urllib.urlopen(url).read()
    f_html = open('tmp%s.html' % str(time.time()), 'w')
    f_html.write(content)
    f_html.close()

def main(urls):
    '''
        main func to be called
    '''
    for url in urls:
        fetch(url)

if __name__ == '__main__':
    FROM_URLS = ['http://www.baidu.com','http://www.sohu.com']
    main(FROM_URLS)

测试报告如下,可以发现此代码最终得到了「10.00/10」,说明代码规范非常不错。

/usr/local/bin/pylint pyl.py
No config file found, using default configuration


Report
======
14 statements analysed.

Statistics by type
------------------

+---------+-------+-----------+-----------+------------+---------+
|type     |number |old number |difference |%documented |%badname |
+=========+=======+===========+===========+============+=========+
|module   |1      |1          |=          |100.00      |0.00     |
+---------+-------+-----------+-----------+------------+---------+
|class    |0      |0          |=          |0           |0        |
+---------+-------+-----------+-----------+------------+---------+
|method   |0      |0          |=          |0           |0        |
+---------+-------+-----------+-----------+------------+---------+
|function |2      |2          |=          |100.00      |0.00     |
+---------+-------+-----------+-----------+------------+---------+



Raw metrics
-----------

+----------+-------+------+---------+-----------+
|type      |number |%     |previous |difference |
+==========+=======+======+=========+===========+
|code      |13     |41.94 |14       |-1.00      |
+----------+-------+------+---------+-----------+
|docstring |10     |32.26 |10       |=          |
+----------+-------+------+---------+-----------+
|comment   |2      |6.45  |2        |=          |
+----------+-------+------+---------+-----------+
|empty     |6      |19.35 |5        |+1.00      |
+----------+-------+------+---------+-----------+



Duplication
-----------

+-------------------------+------+---------+-----------+
|                         |now   |previous |difference |
+=========================+======+=========+===========+
|nb duplicated lines      |0     |0        |=          |
+-------------------------+------+---------+-----------+
|percent duplicated lines |0.000 |0.000    |=          |
+-------------------------+------+---------+-----------+



Messages by category
--------------------

+-----------+-------+---------+-----------+
|type       |number |previous |difference |
+===========+=======+=========+===========+
|convention |0      |1        |-1.00      |
+-----------+-------+---------+-----------+
|refactor   |0      |0        |=          |
+-----------+-------+---------+-----------+
|warning    |0      |0        |=          |
+-----------+-------+---------+-----------+
|error      |0      |0        |=          |
+-----------+-------+---------+-----------+



Global evaluation
-----------------
Your code has been rated at 10.00/10 (previous run: 9.29/10, +0.71)


Process finished with exit code 0

参考资料

  1. Google Python 风格指南 - 中文版
  2. 编写高质量代码 改善Python程序的91个建议
  3. Pycharm download
  4. Running PyLint in PyCharm
  5. Integrate pylint in PyCharm
  6. python代码检查工具pylint-让你的python更规范