Python Code checker tool Pylint make your Python more canonical

Source: Internet
Author: User
1. What is Pylint?

Pylint is a Python Code analysis tool that parses errors in Python code to find code style standards that are not compliant (the code style used by Pylint is PEP 8, specific information, see Resources), and potentially problematic code. Currently the latest version of Pylint is pylint-0.18.1.

Pylint is a Python tool that provides additional functionality in addition to the usual Code analysis tools: Checking the length of a line of code, whether a variable name conforms to a naming standard, whether a declared interface is actually implemented, and so on.
One of the great benefits of Pylint is its high configuration, high customization, and the ability to write small plugins to add functionality.

If you run the Pylint two times, it will show both the current and last run results, so you can see if the code quality has improved.

The Pylint is now integrated into the eclipse's Pydev plugin.

Pylint is a python code-style inspection tool that is based on the standard Guido van Rossum's PEP8.

Pylint is similar to Pychecker, but provides more functionality, such as checking the length of a line of code, checking whether a variable is named to conform to the encoding specification, or checking that the declared interface is actually implemented, see the full check function in http://www.logilab.org/card/ Pylintfeatures.

The biggest advantage of Pylint is its highly configurable and customizable, and you can easily write a small plugin to add personal features.

Installation method: Pip Install Pylint

Reference Links:

Http://www.ibm.com/developerworks/cn/aix/library/au-cleancode/index.html

http://www.douban.com/note/46830857/

Http://zh.wikipedia.org/wiki/Pylint

2, why use Pylint?

In order to write good code. What is good code? Code that fits your team's coding habits: a unified naming, structure.

What is its similar product? Pychecker

What else do you have to add?

3, how to use Pylint?

Basic use:

Through three kinds of code to carry out the test, the score from 1, constantly according to the Pylint prompt reconstruction, and finally get 10 points.
v1_fetch.py:
Copy CodeThe code is as follows:


#coding: Utf-8
Import Urllib
Import time

def a (URL):
Content = Urllib.urlopen (URL). Read ()
f = open (' tmp%s.html '% str (time.time ()), ' W ')
F.write (content)
F.close ()

def main (URLs):
For URL in URLs:
A (URL)

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


Modify the name:
v2_fetch.py:
Copy CodeThe code is as follows:


#coding: Utf-8
Import Urllib
Import time

def 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):
For URL in URLs:
Fetch (URL)

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


Modify again:
v3_fetch.py:
Copy CodeThe code is as follows:


#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)


There are basically several criteria for judging the following:

1. Naming methods

2, DocString

Of course, it is also possible to test packages directly with Pylint: Pylint package

See below for more information on how to use it, so be sure to practice it:

See content:

Call of Pylint

Listing 1. Pylint Call Command
pylint [Options] Module_or_package

Code check for a module module.py using Pylint:
1. Go to the folder where the module is located and run Pylint [options] module.py
This invocation is always working because the current working directory is automatically added to the Python path.

2. Do not enter the folder where the module is located, run Pylint [options] directory/module.py
This invocation can work when the following conditions are met: Directory is a python package (for example, contains a __init__.py file), or directory is added to the Python path.

Code check for a package pakage using Pylint:
1. Go to the folder where the package is located and run Pylint [options] pakage.
This invocation is always working because the current working directory is automatically added to the Python path.

2. Do not enter the folder where the package is located, run Pylint [options] directory/pakage.
In this case, it works 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, where you enter the name of the module or package (the rules and the command line), and the output of the click Run,pylint is displayed in the GUI.
Common command-line arguments for Pylint
-h,–help

Displays all help information.
–generate-rcfile

You can use Pylint–generate-rcfile to generate a sample configuration file. You can use redirection to save this configuration file for later use. You can also precede the other options so that the values of these options are included in the resulting configuration file. such as: Pylint–persistent=n–generate-rcfile > pylint.conf, View pylint.conf, you can see Persistent=no, and no longer is its default value yes.
–rcfile=

Specifies a configuration file. Put the configuration in the configuration file, which not only regulates your own code, but also makes it easy to share these specifications with others.
-I., –include-ids=

Include the ID of the message in the output, and then use pylint–help-msg= to view the details of the error so that you can locate the error specifically.
-R, –reports=

The default is Y, which means that the output of Pylint contains the source Code Analysis section and the report section.
–files-output=

Output the message of each module/package to a pylint_module/package. [Txt|html] In the named file, if there is a report, output to the name Pylint_global. [txt|html] in the file. The default is output to the screen does not output to the file.
-F, –output-format=

Sets the output format. The formats you can choose are text, parseable, colorized, MSVs (Visual Studio) and HTML, and the default output format is text.
–disable-msg=

Suppresses the message of the specified ID. For example, the output contains the message W0402 this warning, if you do not want it to appear in the output, you can use the –disable-msg= W0402
Output of the Pylint
The default output format for Pylint is the raw text format, which can be specified by-F, –output-format=, and other output formats such as HTML. There are two parts in the output of Pylint: The Source Code Analysis section and the reporting section.
Source Code Analysis Section:
For each Python module, the result of Pylint first displays some "*" characters, followed by the name of the module, followed by a series of message, the format of the message is as follows:
Message_type:line_num:[object:] MESSAGE

There are several message_type:
(C) practice. Violates coding style standards
(R) refactoring. Code that was badly written.
(W) warning. Some Python-specific issues.
(E) error. Most likely an error in the code.
(F) Fatal error. Errors that prevent Pylint from running further.

Listing 2. Output of the Utils module in the 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:
After the end of the source code analysis, there will be a series of reports, each focusing on some aspects of the project, such as the number of message per category, the dependency of the module, and so on. Specifically, the report contains the following aspects:
The number of module to check.

For each module, the percentage of errors and warnings in them. For example there are two module A and B, if a total of 4 errors are checked out, 1 errors are in a, 3 errors are in B, then A's error percentage is 25%, B's error percentage is 75%.

The total number of errors, warnings.

Back to top of page
Specific examples of using Pylint to parse Python code
The following is a Python code dw.py that reads some values from an XML file and displays the code as follows:

Listing 3. Source
Import string
#!/usr/bin/env python

Import Xml.dom.minidom

Xmldom=xml.dom.minidom.parse ("Identity.xml")
organizations = Xmldom.getelementsbytagname (' DW ')
for org in organizations:
Products = Org.getelementsbytagname (' Linux ')
For product in Products:
print ' ID: ' + product.getattribute (' id ')
print ' name: ' + product.getattribute (' name ')
print ' Word count: ' + product.getattribute (' count ')

Listing 4. Identity.xml's Content





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

Listing 5. Analysis Results of Pylint
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_]*) | ( __.*__))$)

Omitted from the report section

The first part of the output is source code analysis, and the second part is the report. There is so much information in the output, where do you start the analysis? First use the following steps to analyze the code:
1. Because the output is too long, you can not let it output the report section first, based on the source Code Analysis section to find the problem in the code. Use the option "–reports=n".
2. Use the option "–include-ids=y". You can get the ID of each piece of information into the Source Code Analysis section.

Listing 6. Results of using 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_]*) | ( __.*__))$)

Each message is preceded by an ID, which can be viewed by pylint–help-msg=id if you do not understand the meaning of the message.

Listing 7. Results of using pylint–help-msg= C0111
C0111: *missing docstring*
Used when a module, function, class or method have no docstring. Some Special
Methods like __init__ doesn ' t necessary require a docstring.
This message belongs to the basic checker.

3. Start analyzing the issues in each source code. As you know from above, the first problem is the lack of docstring, the addition of docstring in the code, the following modified code:

Listing 8. Add docstring Modified source code
#!/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 (' DW ')
for org in organizations:
Products = Org.getelementsbytagname (' Linux ')
For product in Products:
print ' ID: ' + product.getattribute (' id ')
print ' name: ' + product.getattribute (' name ')
print ' Word count: ' + product.getattribute (' count ')

Rerun Pylint–reports=n–include-ids=y dw.py with the result:

Listing 9. Run results
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_]*) | ( __.*__))$)

You can see that the first problem in the source code has been resolved.
4. With regard to the second C0322, the analysis here shows that it is clear that there are no spaces on either side of the Equals operator in line seventh of the code. We add a space here, rerun Pylint–reports=n–include-ids=y dw.py, the result is:

Listing 10. Run results
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. You can see that now the problem is only C0103. This means that the variable naming rules should conform to the provisions of the following regular expressions. Pylint defines a series of naming conventions for names of variables, functions, classes, etc. In practice we do not necessarily have to use such a naming convention, we can define our own naming rules using regular expressions, such as using the option –const-rgx= ' [a-z_][a-z0-9_]{2,30}$ ', we change the variable xmldom to XMLDOM, the code is as follows:

Listing 11. Change the variable xmlDom to the source code after 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 (' DW ')
for org in organizations:
Products = Org.getelementsbytagname (' Linux ')
For product in Products:
print ' ID: ' + product.getattribute (' id ')
print ' name: ' + product.getattribute (' name ')
print ' Word count: ' + product.getattribute (' count ')

Run pylint–reports=n–include-ids=y–const-rgx= ' [a-z_][a-z0-9_]{2,30}$ ' dw.py, there is no problem in the results.

6. If you want a group of people to use these uniform rules, to standardize the code style of a department. For example, if you use –const-rgx= ' [a-z_][a-z0-9_]{2,30}$ ' as a naming convention, a convenient way is to use a configuration file.

Use Pylint–generate-rcfile > pylint.conf to generate a sample configuration file, and then edit the –CONST-RGX option in it. Or you can directly pylint–const-rgx= ' [a-z_][a-z0-9_]{2,30}$ ' –generate-rcfile > pylint.conf, so the –CONST-RGX option in the generated configuration file is directly ' [ a-z_][a-z0-9_]{2,30}$ ' out.
Specify the configuration file when running Pylint later: pylint–rcfile=pylint.conf dw.py
The pylint will then specify the parameters according to the options in the configuration file pylint.conf. In one department, you can use the same configuration file together, so that you can maintain a consistent code style.

7. If the report section is added, i.e. without the use of –reports=n, the contents of the reporting section can be seen.

Related to this:

Code Advisor Tool:

Http://www.cnblogs.com/LiGleam/archive/2012/02/19/2358549.html

http://www.ibm.com/developerworks/cn/linux/l-cn-pylint/index.html?ca=drs-cn-1217
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.