Python code scanning: an artifact to improve the quality of Python code - pylint detailed explanation and usage guide

Table of contents

introduce

Features of pylint

Installation & Configuration

Use Cases

Command line parameters

Ignore a file from checking

Ignore the execution type (C, R, W, E, F) in the file and do not check

Ignore the execution type (C, R, W, E, F) of a function in the file and do not check it

Ignore the execution type (C, R, W, E, F) of a certain class in the file and do not check it

Ignore the no-member prompt

Use pylint on the command line: disable=W

Profile configuration

Scan the entire project

Application scenarios of pylint

Reference documentation


Note: Subsequent technology sharing, immediate updates, and more timely technical information and learning technical materials will be releasedon the official account CTO Plus . Please follow the official account: CTO Plus

As an easy-to-learn and powerful programming language, Python has attracted more and more of us. However, due to Python's flexibility and loose syntax rules, code quality control becomes a challenge. To solve this problem, I will introduce a popular tool-pylint, which can help us improve the quality of Python code.

pylint is a Python code inspection tool that can statically analyze Python code and find potential problems. It can not only check the syntax errors of the code, but also check the code style, naming convention, code complexity and other aspects. Based on the PEP 8 specification and other best practices, pylint provides a series of rules to evaluate the quality of the code and give corresponding suggestions and repair methods.

This article "Python Code Scanning: An Artifact to Improve Python Code Quality - Pylint Detailed Explanation and Usage Guide" is the fourth in the series of "Python Code Specifications and Scanning". The first three articles can be consulted according to your own situation. Public accounts are also welcome. CTO Plus follow-up articles:

Code specifications and static scanning series content:

  1. " Static Scanning of Enterprise-Level Python Code - Introduction to Code Specifications, Logic, Grammar, Security Checks, and Automatic Code Arrangement "
  2. " Reading through the Python PEP8 Code Specification "
  3. " Python Code Scanning: New Generation Python Linter Tool Ruff "
  4. " Python code scanning: an artifact to improve the quality of Python code-pylint detailed explanation and usage guide "
  5. " Python Code Scanning: Lightweight Python static code analysis tool pyflakes "
  6. " Python code scanning: a powerful tool for Python code specification and error checking-flake8 detailed explanation and practice "
  7. " Python code scanning: the best choice for static type checking mypy "
  8. " Python code scanning: automatically remove redundancy in Python code-autoflake usage tips and examples "
  9. " Python code scanning: a powerful tool for Python code formatting-yapf detailed explanation and best practices "
  10. " Python code scanning: the black magic of formatting Python code with one click - black usage tutorial "
  11. " Python Code Scanning: Import Statement Automatic Sorting Tool-isor Usage Guide and Examples "
  12. " Python code scanning: a tool to automatically repair Python code style - autopep8 detailed explanation and examples "
  13. " Python code scanning: code specifications and error checking in the project-pyproject-flake8 configuration and usage "
  14. " Python Code Scanning: Enterprise-Level Code Security Vulnerability Scanning Bandit "

introduce

Pylint  is a Python code analysis tool that finds libraries that do not comply with code style standards (the code style used by Pylint by default is PEP 8) and common errors, such as checking the length of a line of code, whether variable names comply with naming standards, and a declared Whether the interface is actually implemented , etc. If the code written does not comply with the PEP-8 coding specification, it will report an error to us. It is integrated into some popular editors and IDEs  , and can also be run standalone from the command line.

You can modify pylint's configuration file and its checking method to make it comply with other coding standards. For example, you can force variable names and function names to become camel case. Using Pylint facilitates the team to form unified coding standards.

Features of pylint

pylint has the following characteristics:

1. Rich set of rules: pylint provides a large number of rules, covering issues such as coding style, naming conventions, and code complexity. We can choose the appropriate rules for checking according to our needs.

2. Customizable rules: pylint supports custom rules. We can define our own rules according to the needs of the project to meet specific code quality requirements.

3. Detailed reports: pylint generates detailed reports that include a description, location, and recommended fix for each issue. These reports can help us quickly locate and solve problems in the code.

4. Easy to integrate: pylint can be integrated with other tools, such as editors, continuous integration systems, etc. It can check the code in real time during the code writing process and check before submitting the code to ensure the quality of the code.

Installation & Configuration

Next we start to install pylint. You can install pylint through the pip command, as shown below:

pip install pylint

  1. Settings in Pycharm

Arguments:$FilePath$

  1. How to specify configuration files in Pycharm

  1. Add parameters in Pycharm to shield custom type checks

disable=W,E,R,C

Use Cases

Run  pylint [options] path/to/dir or  pylint [options] path/to/module.py use Pylint from the command line , and it will print to the console any violations and errors in your code.

You can also use  pylintrc configuration files to customize which code errors Pylint checks for.

Command line parameters

  1. -h, –help

Show all help information.

  1. --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.

pylint --generate-rcfile > pylint.conf

  1. --rcfile=<xx.conf>

Specify a configuration file to run pylint. 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.

pylint --rcfile=pylint.conf dw.py

  1. --reports=<y_or_n>

The default is n, which means that Pylint's output includes not only the source code analysis part, but also the report part.

pylint --rcfile=pylintrc.conf --reports=y main.py

The above format is installed in the report to generate the inspection results. W represents the generated inspection level. The levels are divided into 4 types: error, warning, refactor, and convention; the corresponding level can be determined according to the first letter. “10, 0” represents the line number and column number in the source code file where the alarm is located. "Unused import help" expresses the details of the problem. "(unused-import) is the message ID information of the problem.

The following information is classified according to message categories and summarizes four levels of alarm information:

  1. --help-msg=

Get alarm help information.

If you need to get help information for a certain alarm type, you can use the "pylint --help-msg " command to get it:

pylint --help-msg=C0114

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

  1. --output-format=

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

pylint --output-format=msvs external.py

  1. xx.txt

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

pylint --output-format=msvs external.py > test.txt

Pylint output

The default output format of Pylint is 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, Pylint's results first display some "*" characters, followed by the name of the module, and then a series of messages. The format of the message is as follows:

MESSAGE_TYPE: LINE_NUM:[OBJECT:] MESSAGE

MESSAGE_TYPE has the following types:

(C) Convention. Violates coding style standards

(R) Reconstruction. 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.

Ignore a file from checking

Do not check external.py, set in the file: # pylint: skip-file

# pylint: skip-file

from pysdk.first_layer import BaseLayer

class Events(BaseLayer):

    def __init__(self):

        # pylint: disable=C0115

        super(Events, self).__init__()

class Metrics(BaseLayer):

    def __init__(self):

        super(Metrics, self).__init__()

Ignore the execution type (C, R, W, E, F) in the file and do not check

The 'W' type in external.py is not checked. Set it in the file: # pylint : disable=W

# pylint: disable=W

from pysdk.first_layer import BaseLayer

class Events(BaseLayer):

    def __init__(self):

        super(Events, self).__init__()

class Metrics(BaseLayer):

    def __init__(self):

        super(Metrics, self).__init__()

Ignore the execution type (C, R, W, E, F) of a function in the file and do not check it

The 'W,R,E' type in external.py is not checked. Set it under the function or ordinary function in the file: # pylint: disable=W,E, R

from pysdk.first_layer import BaseLayer

class Events(BaseLayer):

    def __init__(self):

        # pylint: disable=W,R,E

        super(Events, self).__init__()

    def __init__(self):

        super(Events, self).__init__()

class Metrics(BaseLayer):

    def __init__(self):

        super(Metrics, self).__init__()

Ignore the execution type (C, R, W, E, F) of a certain class in the file and do not check it

The 'W,R,E' type in external.py is not checked. Set it under the class in the file: # pylint: disable=C,F,W,E, R

from pysdk.first_layer import BaseLayer

class Events(BaseLayer):

    # pylint: disable=C,R,W,E,F

    def __init__(self):

        super(Events, self).__init__()

    def __init__(self):

        super(Events, self).__init__()

class Metrics(BaseLayer):

    def __init__(self):

        super(Metrics, self).__init__()

Ignore the no-member prompt

Code modification #pylint: disable=no-member

pylint --disable=no-member ...

Use pylint on the command line : disable=W

  1. Do not disable specified types

pylint + target project or file

Write test code files

Execute pylint

Results of the

If the code is rectified to the standards and the rectified code is scanned again, you will see that there is no detection status and the score is 10.

Or execute pylint pylint_test.py in the command line

  1. Disable W type

pylint --disable=W external.py

Profile configuration

Generate the configuration file pylintrc.conf in the project root directory

pylint --generate-rcfile > pylintrc.conf

pylint --persistent=n --generate-rcfile > pylintrc.conf

  1. Carrying configuration files for scanning of individual files

pylint --rcfile=pylintrc.conf manage.py

  1. Disable the specified item

Configure to disable warnings and configure to disable checking of specified items.

Several states of pylint: Error (Error) Warning (Warning) Refactor (Reconstruction) Convention (Specification)

--disable=W,E,R,C

--disable=E,R,C

--disable=E,R

After disabling the R0801 item and scanning again, you will see that inconsistent results will no longer be output.

  1. pylint sets the number of characters detected per line

For modification of the number of characters per line, the default is 100

Note: Rename pylint.conf to .pylintrc , that is, there is no need to bring the --rcfile parameter with each execution .

Scan the entire project

Right-click in the project root directory and select pylint execution

When using pylint, there are the following prompt levels: Error, Warning, Refactor, and Convention.

The output results include: the position (column) that conflicts with the specification, the specification number that is violated, and the specific content prompt. A score will be given based on the detection result, with a total score of 10 points.

From the inspection information, we can see that the above code lacks module comments (Missing module docstring) and function comments (Missing function docstring), and the function name does not comply with the snake-shaped naming convention (all composed of lowercase letters and underscores, with a use between the two words (downline connection) etc.

Application scenarios of pylint

pylint can be applied in many projects, especially in large projects and team collaboration. The following are some application scenarios of pylint:

1. Code specifications: For projects that follow the PEP 8 specification, pylint can help us check whether the code style complies with the specification and provide corresponding repair suggestions.

2. Code quality: pylint can help us check some common problems in the code, such as unused variables, unused imports and duplicate code, etc., to improve the quality and maintainability of the code.

3. Team collaboration: In team collaboration, pylint can help us unify code style and quality standards to improve code consistency and readability.

4. Continuous integration: In a continuous integration environment, pylint can be used as a checking step to help us find problems before the code is submitted to avoid merging wrong code into the main branch.

Reference documentation

  1. Official documentation: http://pylint.pycqa.org/en/latest/user_guide/output.html
  2. pylint:https://pylint.readthedocs.io/en/latest/user_guide/usage/run.html
  3. Python code specifications: Enterprise-level code static scanning - code specifications, logic, syntax, security checks, and automatic arrangement of code specifications (1)_pycharm Check code specifications_SteveRocket's blog-CSDN blog
  4. https://blog.csdn.net/zhouruifu2015/article/details/129877179

Python column
https://blog.csdn.net/zhouruifu2015/category_5742543


More information · Search the WeChat public account [ CTO Plus ] and follow it to get more information. Let’s learn and communicate together.

For a description of the public account, visit the following link


For more exciting news, follow my official account and learn and grow together.

About Articulate "Be a porter of knowledge and technology. Be a lifelong learning enthusiast. Be a technical circle with depth and breadth." I have always wanted to develop skills in the professional field icon-default.png?t=N7T8https://mp.weixin.qq. com/s?__biz=MzIyMzQ5MTY4OQ==&mid=2247484278&idx=1&sn=2b774f789b4c7a2ccf10e465a1b9def6&chksm=e81c2070df6ba966026fd7851efa824b5e2704e3fd34e 76228ca4ce64d93f7964cd4abe60f2b#rd

Standard Library Series-Recommended Reading:

Recommended
reading:

Guess you like

Origin blog.csdn.net/zhouruifu2015/article/details/132831978