Python code checker pylint make your python more normative _python

Source: Internet
Author: User
Tags naming convention in python
1, what is Pylint?

Pylint is a Python Code analysis tool that analyzes errors in Python code and finds code-style standards that are not compliant (Pylint's default code style is PEP 8, specific information, see Resources), and potentially problematic code. The latest version of the current 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 scalability, high customization, and easy to write widgets to add functionality.

If you run the Pylint two times, it displays both current and last run results to see if the code quality has improved.

Pylint is also integrated into Eclipse's Pydev plug-in.

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 lines of code, checking whether variable naming conforms to coding specifications, or checking whether the declared interface is truly implemented, and complete inspection features see http://www.logilab.org/card/ Pylintfeatures.

The biggest advantage of Pylint is its highly configurable and customizable, and you can easily write a widget 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 conforms to the coding habits of the team: uniform 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 on the test, the score from 1, unceasingly according to Pylint's prompt to reconstruct, finally obtains 10 points.
v1_fetch.py:
Copy Code code 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)

To modify a name:
v2_fetch.py:
Copy Code code 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 Code code 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 is 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 the following criteria for judging:

1. Naming method

2, DocString

Of course, directly with Pylint for packet detection is also possible: Pylint package

See below for more ways to use, be sure to practice to do it:

Refer to the content:

Call to Pylint

Listing 1. Call command for Pylint
pylint [Options] Module_or_package

Code-check a module module.py using Pylint:
1. Enter the folder where this module is located, 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 true: directory is a python package (including a __init__.py file), or directory is added to the Python path.

Use Pylint to perform a code check on a package pakage:
1. Enter the folder where this 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 tkinter packs, you can use the command Pylint-gui to open a simple GUI interface, where you enter the module or package name (the rules are the same as the command line), and the Run,pylint output 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 an example of a 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. For example: Pylint–persistent=n–generate-rcfile > pylint.conf, View pylint.conf, you can see Persistent=no, not its default value yes.
–rcfile=

Specifies a configuration file. Use the configuration in the configuration file, so not only to standardize their own code, you can easily share these specifications with others.
-I, –include-ids=

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

The default is Y, which means that the output of Pylint contains the part of the source code analysis, as well as the report section.
–files-output=

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

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

Suppresses the specified ID message. For example, the output contains the message W0402 this warning, if you do not want it to appear in the output, you can use –disable-msg= W0402
The output of the Pylint
The default output format for Pylint is the raw text format, which allows you to specify other output formats, such as HTML, through-F, –output-format=, and so on. The Pylint output has the following two parts: 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 formats as follows:
Message_type:line_num:[object:] Message

There are several message_type:
(C) practice. Violates the coding style standard
(R) refactoring. Very poorly written code.
(W) warning. Some Python-specific issues.
(E) error. It is most likely the error in the code.
(F) Fatal error. An error that prevents Pylint from running further.

Listing 2. Output results of utils modules 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:
After the end of the source analysis, there will be a series of reports that focus on some aspects of the project, such as the number of message types per category, the dependencies of the modules, and so on. Specifically, the report will include the following:
The number of module checks.

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, 1 errors are in A, 3 errors are in B, then A's error percentage is 25%, B's error percentage is 75%.

Error, total number of warnings.

Back to the top of the page
Use Pylint to analyze specific examples of Python code
Here is a snippet of Python code dw.py that reads some values from an XML file and displays them 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. The content of Identity.xml





The result of using Pylint, 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_]*) | ( __.*__))$)

Part of the section omitted

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 to analyze it? First, use the following steps to analyze your code:
1. Because the output is too long, you can not let it output the report section, first, according to the Source Code Analysis section to find out 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 in the Source Code Analysis section.

Listing 6. Using the results of 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, and if you do not understand the meaning of this information, you can view it through Pylint–help-msg=id.

Listing 7. Using the results of 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 is belongs to the basic checker.

3. Start to analyze problems in each source code. As you know from the above, the first problem is due to the lack of docstring, adding docstring to the code, and the modified code as follows:

Listing 8. Increase the 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, and the result is:

Listing 9. Run results
Module DW
C0322:7: Operator not preceded by a
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. On the question of the second C0322, the analysis here shows that there are no spaces on either side of the Equals operator on line seventh of the code. We add a space here, rerun Pylint–reports=n–include-ids=y dw.py, and 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. It can be seen that the problem remains C0103. This means that the variable naming rules should conform to the rules of the following regular expressions. Pylint defines a series of naming conventions for names of variables, functions, classes, and so on. In practice, we do not necessarily use such naming rules, 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 xmldom after the 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 ')

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, everyone uses –const-rgx= ' [a-z_][a-z0-9_]{2,30}$ ' as the naming convention, and a more convenient approach 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. Alternatively, you can directly pylint–const-rgx= ' [a-z_][a-z0-9_]{2,30}$ ' –generate-rcfile > pylint.conf, so that the –CONST-RGX option in the generated configuration file is directly ' [ a-z_][a-z0-9_]{2,30}$ ' up.
Specify a profile when you run Pylint later: pylint–rcfile=pylint.conf dw.py
This allows pylint to specify the parameters according to the options in the configuration file pylint.conf. In one department, you can use the same profile together so that you can maintain a consistent code style.

7. If the report section is added, that is, the –reports=n is not used, the contents of the reporting section can be seen.

Associated with this:

Code Advisor Tools:

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
Related Article

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.