How to use Pylint to standardize Python code style (from IBM)_python

不言
Release: 2018-04-08 11:13:34
Original
2244 people have browsed it

This article provides a comprehensive introduction to the Python code analysis tool Pylint through a detailed theoretical introduction and easy-to-understand examples. I believe that readers will be able to easily apply Pylint to their own development projects after reading this

What is Pylint

Pylint is a Python code analysis tool that analyzes Python Errors in the code, looking for code that does not comply with coding style standards (the coding style used by Pylint by default is PEP 8, see Resources for specific information) and potentially problematic code. The latest version of Pylint is currently pylint-0.18.1.

  • Pylint is a Python tool. In addition to the functions of ordinary code analysis tools, it provides more functions: such as checking the length of a line of code, whether the variable name meets the naming standards, Whether a declared interface is actually implemented, etc.

  • One of the great benefits of Pylint is that it is highly configurable, highly customizable, and it is easy to write small plug-ins to add functionality.

  • If you run Pylint twice, it will display the results of the current and last runs at the same time, so you can see whether the code quality has been improved.

  • Pylint is currently integrated into the pydev plug-in of eclipse.

Pylint detailed introduction

Pylint installation

Pylint can be used for all Python versions higher than or equal to 2.2 and is compatible . The packages logilab-astng (version >= 0.14) and logilab-common (version >= 0.13) are required (see Resources for specific information). If the Python version is lower than 2.3, then it also requires the optik package (this article The following examples will not consider this case).

The download address of all packages used by Pylint

The latest package download of logilab-astng: http://www.logilab.org/856/

logilab-common’s latest package download: http://www.logilab.org/848/

optik’s package download: http://optik.sourceforge.net/

## Download the latest package of #Pylint: http://www.logilab.org/project/pylint

Pylint installation on Linux

1. On Linux, First install the Python package (above version 2.2) and add the path to the Python executable file in the environment variable $PATH.

2. Download the packages of Pylint, logilab-astng (version >= 0.14) and logilab-common (version >= 0.13), and use tar zxvf *.tar.gz to decompress these packages.
3. Enter the folders where logilab-astng, logilab-common and Pylint were extracted in order, and run the command Python setup.py install to install.
4. After the installation is complete, you can call Pylint through pylint [options] module_or_package.

Installation of Pylint on Windows

1. Install the Python package (above version 2.2), right-click the My Computer icon on the desktop and select Properties , Advanced, environment variables, add the Python installation path in $PATH, such as C:\Python26\.

2. Use the decompression tool to decompress all packages.
3. Open the command line window, use cd to enter the unpacked folders of logilab-astng, logilab-common and Pylint in sequence, and run the command python setup.py install to install.
4. After the installation is completed, a Scripts folder will appear in the Python installation path, which contains some bat scripts, such as pylint.bat, etc.
5. In order to avoid entering the full path when calling pylint.bat, create a redirection file of pylint.bat in the Python installation directory. This is a plain text file pylint.bat, which contains pylint.bat. Actual path, such as: C:\Python26\Scripts\pylint.bat.
6. After the installation is complete, you can call Pylint through pylint [options] module_or_package.

Pylint calling

List 1. Pylint calling command


##pylint [options] module_or_package

Use Pylint to check the code of a module module.py:

    1. Enter the folder where the module is located and run
  • pylint [options] module.py

    This method of calling will always work because the current working directory will be automatically added to the Python path.

  • 2. Without entering the folder where the module is located, run
  • pylint [options] directory/module.py

    This calling method is used when the following conditions are met It will work if the directory is a Python package (for example, contains an __init__.py file), or if the directory is added to the Python path. <br>

  • Use Pylint to check the code of a package:

    1. Enter the folder where the package is located and run
  • pylint [options ] pakage

    . This method of calling will always work because the current working directory will be automatically added to the Python path.

  • 2. Without entering the folder where the package is located, run
  • pylint [options] directory/ pakage

    . In this case, it can work when the following conditions are met: directory is added to the Python path. For example, on Linux, export PYTHONPATH=$PYTHONPATH: directory.

In addition, for machines with the tkinter package installed, you can use the command pylint-gui to open a simple GUI interface, enter the name of the module or package here (the rules are the same as the command line), and click Run. Pylint's output is displayed in the GUI.

Pylint’s common command line parameters

  • -h,--help

    Display all help information.

  • --generate-rcfile

    You can use pylint --generate-rcfile to generate an example configuration file. You can use redirection to save this configuration file for later use. You can also add other options in front so that the values ​​of these options are included in the generated configuration file. For example: pylint --persistent=n --generate-rcfile > pylint.conf. If you look at pylint.conf, you can see that persistent=no is no longer its default value of yes.

  • --rcfile=

    Specify a configuration file. Put the configuration you use in the configuration file, which not only standardizes your own code, but also makes it easy to share these specifications with others.

  • -i , --include-ids=

    Include the message id in the output, and then pass pylint --help- msg= to view the detailed information of this error so that you can specifically locate the error.

  • ##-r , --reports=

    The default is y, which means that in addition to the source code analysis part, Pylint's output also Contains reporting section.

  • --files-output=

    Output the message of each module/package to a file named pylint_module/package.[txt|html] In the file, if there is a report, it will be output to a file named pylint_global.[txt|html]. The default is to output to the screen and not to a file.

  • -f , --output-format=

    Set the output format. The formats that can be selected are text, parseable, colorized, msvs (visual studio) and html. The default output format is text.

  • --disable-msg=

    Disable messages with specified ids. For example, if the output contains the warning message W0402, if you do not want It appears in the output, you can use --disable-msg= W0402

Output of Pylint

The default output format of Pylint is raw text (raw text) format, you can use -f , --output-format= to specify other output formats such as html, etc. There are two parts in the output of Pylint: the source code analysis part and the report part.

Source code analysis part:

For each Python module, the Pylint result first displays some "*" characters, followed by the name of the module, and then A series of messages, the format of message is as follows:

MESSAGE_TYPE: LINE_NUM:[OBJECT:] MESSAGE

MESSAGE_TYPE has the following types:

(C) Convention. Violation of Coding Style Standard

(R) Refactoring. Very poorly written code.
(W) Warning. Some Python specific questions.
(E) Error. Most likely a bug in the code.
(F) Fatal error. An error that prevents Pylint from running further.

Listing 2. Output of the utils module in Pylint

****************** Module utils

C: 88 :Message: Missing docstring
R: 88:Message: Too few public methods (0/2)
C:183:MessagesHandlerMixIn._cat_ids: Missing docstring
R:183:MessagesHandlerMixIn._cat_ids: Method could be a function
R:282:MessagesHandlerMixIn.list_messages: Too many branches (14/12)

Report section:

End of source code analysis Later, there will be a series of reports, each report focusing on certain aspects of the project, such as the number of messages in each category, module dependencies, etc. Specifically, the report will include the following aspects:

  • The number of modules checked.

  • For each module, the percentage of errors and warnings. For example, there are two modules A and B. If a total of 4 errors are detected, 1 error is in A and 3 errors are in B, then the error percentage of A is 25% and the error percentage of B is 75 %.

  • The total number of errors and warnings.

Specific example of using Pylint to analyze Python code

The following is a Python code that reads some values ​​from an xml file and displays them dw.py, the code is as follows:

Listing 3. Source code


import string 
 #!/usr/bin/env python 
 
 import xml.dom.minidom 
 
 xmlDom=xml.dom.minidom.parse("identity.xml") 
 organizations = xmlDom.getElementsByTagName(&#39;DW&#39;) 
 for org in organizations: 
  products = org.getElementsByTagName(&#39;linux&#39;) 
 for product in products: 
  print &#39;ID: &#39; + product.getAttribute(&#39;id&#39;) 
  print &#39;Name: &#39; + product.getAttribute(&#39;name&#39;) 
  print &#39;Word Count: &#39; + product.getAttribute(&#39;count&#39;)
Copy after login


Listing 4. Contents of identity.xml


<IBM> 
  <DW> 
    <linux id="100" name="python" count="3000" /> 
  </DW> 
</IBM>
Copy after login


The result of using Pylint at this time (this is copied from the output in html format) is:

Listing 5. Pylint analysis results

************* Module dw
C:1:Missing docstring
C:5:Operator not preceded by a space xmlDom=xml.dom.minidom.parse("identity.xml") ^
C:5:Invalid name "xmlDom" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)
C:6:Invalid name "organizations" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)

Report 部分省略

输出中第一部分是源代码分析,第二部分是报告。输出结果中有这么多信息,从哪里开始分析呢?首先使用如下的步骤来分析代码:

1. 因为输出结果太长,所以可以先不让它输出报告部分,先根据源代码分析部分来找出代码中的问题。使用选项 "--reports=n"。
2. 使用选项 "--include-ids=y"。可以获取到源代码分析部分每条信息的 ID。

清单 6. 使用 pylint --reports=n --include-ids=y dw.py 的结果

************* Module dw
C0111: 1: Missing docstring
C0322: 5: Operator not preceded by a space xmlDom=xml.dom.minidom.parse("identity.xml") ^
C0103: 5: Invalid name "xmlDom" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)
C0103: 6: Invalid name "organizations" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)

每个信息前面都会加上一个 id, 如果不理解这个信息的意思,可以通过 pylint --help-msg=id来查看。

清单 7. 使用 pylint --help-msg= C0111 的结果

C0111: *Missing docstring*
Used when a module, function, class or method has no docstring. Some special
methods like __init__ doesn't necessary require a docstring.
This message belongs to the basic checker.

3. 开始分析每个源代码中的问题。从上面知道,第一个问题的原因是缺少 docstring,在代码中增加 docstring, 修改后的代码如下:

清单 8. 增加 docstring 修改后的源码


#!/usr/bin/env python 
 
"""This script parse the content of a xml file"""
 
 import xml.dom.minidom 
 
 xmlDom=xml.dom.minidom.parse("identity.xml") 
 organizations = xmlDom.getElementsByTagName(&#39;DW&#39;) 
 for org in organizations: 
 products = org.getElementsByTagName(&#39;linux&#39;) 
 for product in products: 
  print &#39;ID: &#39; + product.getAttribute(&#39;id&#39;) 
  print &#39;Name: &#39; + product.getAttribute(&#39;name&#39;) 
  print &#39;Word Count: &#39; + product.getAttribute(&#39;count&#39;)
Copy after login


重新运行 pylint --reports=n --include-ids=y dw.py,结果为:

清单 9. 运行结果

************* Module dw
C0322: 7: Operator not preceded by a space
xmlDom=xml.dom.minidom.parse("identity.xml")
^
C0103: 7: Invalid name "xmlDom" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)
C0103: 8: Invalid name "organizations" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)

可以看到源代码中的第一个问题已被解决。

4. 关于第二个 C0322 的问题,这里的分析结果说明得比较清楚,是代码第七行中的等号运算符两边没有空格。我们在这里加上空格,重新运行 pylint --reports=n --include-ids=y dw.py,结果为:

清单 10. 运行结果

************* Module dw
C0103: 7: Invalid name "xmlDom" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)
C0103: 8: Invalid name "organizations" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)

5. 可以看到现在问题只剩下 C0103 了。这里的意思是变量命名规则应该符合后面正则表达式的规定。Pylint 定义了一系列针对变量,函数,类等的名字的命名规则。实际中我们不一定要使用这样的命名规则,我们可以定义使用正则表达式定义自己的命名规则,比如使用选项 --const-rgx='[a-z_][a-z0-9_]{2,30}$',我们将变量 xmlDom改为 xmldom, 代码如下:

清单 11. 将变量 xmlDom 改为 xmldom 后的源码


#!/usr/bin/env python 
 
"""This script parse the content of a xml file"""
 
 import xml.dom.minidom 
 
 xmldom = xml.dom.minidom.parse("identity.xml") 
 organizations = xmldom.getElementsByTagName(&#39;DW&#39;) 
 for org in organizations: 
 products = org.getElementsByTagName(&#39;linux&#39;) 
 for product in products: 
  print &#39;ID: &#39; + product.getAttribute(&#39;id&#39;) 
  print &#39;Name: &#39; + product.getAttribute(&#39;name&#39;) 
  print &#39;Word Count: &#39; + product.getAttribute(&#39;count&#39;)
Copy after login


运行 pylint --reports=n --include-ids=y --const-rgx='[a-z_][a-z0-9_]{2,30}$' dw.py,结果中就没有任何问题了。

6. 如果希望一个组里的人都使用这些统一的规则,来规范一个部门的代码风格。比如说大家都使用 --const-rgx='[a-z_][a-z0-9_]{2,30}$'作为命名规则,那么一个比较便捷的方法是使用配置文件。
使用 pylint --generate-rcfile > pylint.conf来生成一个示例配置文件,然后编辑其中的 --const-rgx选项。或者也可以直接 pylint --const-rgx='[a-z_][a-z0-9_]{2,30}$' --generate-rcfile > pylint.conf,这样生成的配置文件中 --const-rgx选项直接就是 '[a-z_][a-z0-9_]{2,30}$'了。
以后运行 Pylint 的时候指定配置文件:pylint --rcfile=pylint.conf dw.py
这样 Pylint 就会按照配置文件 pylint.conf中的选项来指定参数。在一个部门中,大家可以共同使用同一个配置文件,这样就可以保持一致的代码风格。

7. 如果把 report 部分加上,即不使用 --reports=n,可以看到报告部分的内容。

结束语

This article provides a comprehensive introduction to the Python code analysis tool Pylint through a detailed theoretical introduction and easy-to-understand examples. I believe that readers will be able to easily apply Pylint to their own development projects after reading this.

Related Topics

  • Pylint official website. Download the latest package of

  • logilab-astng. Download the latest package of

  • logilab-common.

  • optik package download.

  • The latest package download of Pylint.

  • View the Python code style standard PEP 8 -- Style Guide for Python Code download.

  • For more information about Python, please refer to the Python topic on developerWorks.

Related recommendations:

python code checking tool pylint makes your python more standardized

The above is the detailed content of How to use Pylint to standardize Python code style (from IBM)_python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!