Python code scanning: a powerful tool for Python code specification and error checking - flake8 detailed explanation and practice

 

Table of contents

introduce

Features of flake8

Installation & Configuration

Experience

Command line parameters

Used in PyCharm

Used in command line

Scan items using configuration files

Mask the specified check item in the specified line of code

References


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

In Python development, code specifications and error checking are very important aspects. Good code specifications can improve the readability and maintainability of the code, and error checking can help us find and fix potential problems in time. Among the many code specification and error checking tools, flake8 is a popular and powerful tool. In this article, I will introduce in detail the characteristics, usage and practical experience of flake8.

This article "Python Code Scanning: A powerful tool for Python code specification and error checking - Detailed explanation and practice of flake8" belongs to the sixth article in the series of "Python Code Specification and Scanning". The first five articles can be consulted according to your own situation. The public is also welcome No. 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

Flake8 is a tool officially released by Python to assist in checking whether Python code is standardized. Compared with Pylint, which is currently relatively popular, Flake8 has flexible checking rules, supports the integration of additional plug-ins, and has strong scalability. Programs can be written to implement code compliance testing.

Similar to Pylint, Flake8 allows you to customize the checked content through configuration files . It has very clear documentation and includes some useful commit hooks to incorporate automatic code checking into your development workflow.

Flake8 can also be integrated into some popular editors and IDEs, such as PyCharm, which will be introduced in later chapters.

Flake8  consists of three code libraries and is "a Python tool that integrates PEP 8, pycodestyle, Pyflakes, Pylint, McCabe (code complexity checker) and third-party plug-ins to check Python code style and quality."

Ned Batchelder's McCabe script is a Python code analysis tool used to calculate the McCabe complexity of a function. McCabe complexity is a measure of code complexity based on the number of nodes and branches in a flowchart. Batchelder 's script uses an AST (Abstract Syntax Tree) to analyze a Python function and calculate its McCabe complexity. This tool can be used to assess code maintainability and understand complexity.

Features of flake8

flake8 is a Python code specification and error checking tool that integrates multiple tools and has the following features:

1. Strong comprehensiveness: flake8 integrates multiple tools, including pycodestyle, pyflakes and McCabe, etc., which can check multiple problems in the code at one time. This can reduce tool installation and configuration and improve development efficiency.

2. Flexible and customizable: flake8 provides a wealth of configuration options that can be customized according to project needs. We can set rules and ignore lists through configuration files or command line parameters to suit different projects and teams.

3. Easy to integrate: flake8 can be integrated with other tools and environments, such as editors, continuous integration systems and code review tools. In this way, the code can be checked in real time during the development process, and feedback can be given in a timely manner to improve code quality.

4. Strong scalability: flake8 supports custom plug-ins, and we can define our own inspection rules according to our own needs. This allows flake8 to adapt to the needs of different projects and teams.

Installation & Configuration

We can use PIP installation in our own virtual environment: pip install flake8

Configure Flake8 in PyCharm

We can still configure the flake8 detection tool in our IDE editor like the previous Ruff and pylint tools. The configuration is as follows:

name: Flake8 (just write one)

Program: `$PyInterpreterDirectory$/python`

Arguments: -m flake8 --max-line-length=130 --exclude venv,migrations $ProjectFileDir$ (can be configured according to your own needs)

Working directory: `$ProjectFileDir$`

Experience

In the actual use of flake8, the inspection effect can be improved based on the following experience:

1. Configure rules: According to the needs of the project, rules and ignore lists can be set through configuration files or command line parameters. You can refer to flake8's official documentation and community experience to choose the rules that suit your project.

2. Regular inspection: It is recommended to inspect the code regularly to maintain the quality and maintainability of the code. Checks can be performed before code submission or in a continuous integration environment to help us find and fix problems in time.

3. Pay attention to warnings: In addition to errors, flake8 will also output warning messages. Sometimes a warning might not be a serious problem, but it's worth paying attention to. You can decide whether to fix the warning based on the needs of your project.

4. Integrate with editor: It is recommended to integrate flake8 in the editor to check the code in real time during the development process. Many popular editors, such as VS Code and PyCharm, offer plugins and integration features for flake8.

Next I will introduce the use of this piece

Command line parameters

Here I summarize some commonly used command line parameters of the Flake8 tool. For others, please refer to the official documentation:

--max-line-length=<length>: Set the maximum number of characters per line, the default is 79.

--ignore=<errors>: Set the error codes to be ignored. Multiple error codes are separated by commas.

--exclude=<patterns>: Set file or directory patterns to exclude.

--filename=<patterns>: Set the file or directory patterns to be checked.

--max-complexity=<number>: Set the maximum complexity of the function, the default is 10.

--select=<errors>: Set the error codes to be checked. Multiple error codes are separated by commas.

Used in PyCharm

In the project that needs to be checked, right-click and select the external tool Flake8. At this time, some problems with our code will be output.

You can also exclude scanning of specified directories by setting: $FilePath$ --exclude templates_module

Used in command line

  1. For the entire project file

If you want to check the entire project, just execute the flake8 command directly in the project root directory, or bring the specified directory

flake8 [options] path/to/dir 

  1. for a single file

We can also perform code detection on a specified single file

flake8 [options] path/to/module.py 

flake8 pylint_test.py

  1. Perform single file detection for a certain inspection item

If we only want to detect a certain check item, we can specify it through the parameter select

flake8 --select=F401 filename.py

Among them, --select=F401 means to check only unused variables, and filename.py means the name of the Python file to be checked.

Scan items using configuration files

We can create a new .flake8 file in the root directory of the project. When we specify the flake8 tool, it will look for the configuration file in the root directory by default, and then scan the project based on this configuration file.

Mask the specified check item in the specified line of code

If we want to block the detection of a specified line in the code and the detection of specified detection items, flake8 can also easily achieve this.

We can do this by using comments and noqa on specific lines of code: # noqa: F405

Just change it to the following

Ways to ignore all errors for the entire file :

We can also add #flake8: noqa at the beginning of the file to prevent any detection of this file.

noqa has no way of putting code-specific comments at the top of the file like in separate lines. #flake8: noqa: F401 may appear to work at first glance, but is actually only detected as #flake8: noqa, which means "ignore all messages in the file".

Overall, flake8 is a popular and powerful Python code specification and error checking tool that can help us improve the quality and maintainability of our code. It is comprehensive, flexible and customizable, easy to integrate and highly scalable. By using flake8, we can check out multiple problems in the code at once and fix them in time. Let's use flake8 together to create standardized and high-quality Python code!

References

  1. flake8配置:Configuring Flake8 — flake8 6.1.0 documentation
  2. flake8钩子:Using Version Control Hooks — flake8 6.1.0 documentation
  3. Flake8: Your Tool For Style Guide Enforcement — flake8 6.1.0 documentation
  4. GitHub - PyCQA/flake8: flake8 is a python tool that glues together pycodestyle, pyflakes, mccabe, and third-party plugins to check the style and quality of some python code.
  5. https://flake8.pycqa.org/en/latest/index.html#quickstart
  6. https://github.com/pycqa/flake8/blob/main/docs/source/index.rst
  7. Full Listing of Options and Their Descriptions — flake8 6.1.0 documentation
  8. Pylint 3.0.0a8-dev0 documentation
  9. Full Listing of Options and Their Descriptions — flake8 4.0.1 documentation
  10. 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
  11. 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/131264442