The black magic of formatting Python code with one click - black usage tutorial

Table of contents

introduce

Characteristics of black

Installation & Configuration

Configuring black in Pycharm

The use and best practices of black

Command line parameters

Scan the specified directory or file

at last

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

In the field of Python programming, code readability and standardization are very important, because good code can improve the efficiency of teamwork, reduce maintenance costs, and facilitate continuous integration and deployment of code. In order to maintain code consistency and standardization, the Python community has developed many tools and specifications. One of the very well-known tools is black.

black is a popular automated Python code formatting tool that can help developers automatically format Python code to comply with the PEP 8 specification. It can automatically adjust the format of the code according to a series of rules, making the code more tidy, readable and consistent. This tool is used frequently in my product development.

It aims to enforce the use of PEP 8 (Python Coding Style Guide) specifications and does not require any manual intervention on our part. black uses a strategy called "uncompromising code formatter", which automatically formats code without taking into account any personal preference or project style.

This article "Python Code Scanning: The Black Magic of One-Click Formatting Python Code - Black Usage Tutorial" belongs to the tenth article in the "Python Code Specification and Scanning" series. The first nine 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

The Python3 black tool is a powerful automated code formatting tool that can improve the readability and standardization of code and reduce the difficulty of team collaboration. By automatically formatting code and using black coding style, we can maintain code consistency, improve team collaboration efficiency, and improve project maintainability. Following best practices and having good communication and consultation with team members, integrating black into our daily development process will bring us a better development experience and code quality.

Black  is relatively new among code inspection tools. It is similar to Autopep8 and Yapf, but more limited and does not have many customization options. The advantage of this is that you don't need to decide what coding style to use, just let Black make the decision.

Black relies on Python 3.6+, but it can format code written in Python 2.

Characteristics of black

black can be easily integrated into development workflows with the following features and benefits:

The characteristics of black include automation, consistency and simplicity, which can reduce the time of code review and discussion and improve the efficiency of team collaboration.

1. Automated formatting: black will automatically detect syntax, indentation, blank lines, line breaks and other issues in the code, and make adjustments according to PEP 8 specifications. This reduces our workload of manually formatting code and ensures code consistency and readability.

2. Black configuration options require little or no configuration: The design concept of black is to make all code formats the same, so there are no configuration options. In this way, everyone in the team can use the same black code style, which reduces the problem of inconsistent code formats due to personal preferences and avoids inconsistent format specifications due to too many configuration options.

3. Easy to integrate: black can be easily integrated with other development tools, such as editors, IDEs, code libraries, etc. Many popular code editors and IDEs (such as VS Code, PyCharm, Sublime Text) provide plug-ins or integrations for black, allowing us to automatically use black for formatting when saving code.

4. Extensibility: black supports many customization options and ignore rules to meet the needs of different projects. We can adjust the behavior of black to suit the specific requirements of the project by formulating specific options.

5. Enforce the use of team norms: black ensures that the entire team uses the same coding style, avoiding code format disputes among team members. This is important for maintaining a high-quality code base and improving team collaboration.

Installation & Configuration

Black can be installed using pip through the following command , execute:

 pip install black 

If you use conda as your package manager, you can install Black using the following command:

conda install -c conda-forge black

After installation, you can see the executable file black.exe in the Scripts directory.

Configuring black in Pycharm

For other configuration options, please refer to the official documentation. For configuration in IDE PyCharm, please refer to the previous usage configuration of Ruff and pylint. The following are my configuration options

After configuration, you can use black in external tools

Next, I will share my practice of using black.

The use and best practices of black

For the best results and experience when using Black for Python code formatting, consider the following best practices:

1. Use version control in projects: Using version control (such as Git) in projects can help us better manage code and retain historical records. Before using black, make sure our code has been committed to the version control repository and create a new branch for formatting.

2. Preview and compare changes, and pay attention to the formatting results: Before running black, it is recommended that we preview the upcoming changes. black provides a `--diff` option that displays the differences for each file to be changed. This provides a better understanding of how black will change the code and confirms that the changes are as expected. Because although Black can automatically format code, it may sometimes produce unexpected results. Therefore, after performing the formatting operation, it is recommended to carefully check the formatting results to ensure that the readability and maintainability of the code are not affected.

3. Batch formatting: black can batch format the code of the entire project. You can use the `black .` command to format all Python files in the current directory and subdirectories. Please note that this will directly update the contents of the file, please make sure you have backed up our code before running it.

4. Configure editor plug-ins: Most popular editors (such as VS Code, PyCharm, etc.) and IDEs provide black plug-ins or integrations. Installing and configuring appropriate plug-ins can automatically run black for formatting when saving code, and provide timely feedback to improve code quality.

5. Follow team norms: black is a tool for team norms, so the rules for using black must be established in the project or team, including what options and rules to use, and shared with team members.

6. Combined with lint tools: Last but not least, Black can also be used in combination with other lint tools (such as flake8, pylint, etc.) to further improve the quality of the code. The lint tool can help check for potential problems in the code, and when used with Black, it can better ensure that the code is readable and maintainable.

Command line parameters

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

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

--skip-string-normalization: Skip normalization of strings.

--include=<patterns>: Set the file or directory patterns to be included.

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

Scan the specified directory or file

 You can use Black black path/to/dir to  optimize your code.black path/to/module.py 

Format a single file

A single Python file can be formatted using the following command :

black /path/to/file.py

Scan a single file in PyCharm

This will directly modify the code in the file to conform to the PEP 8 specification.

Format the entire directory

All Python files in an entire directory can be formatted using the following command:

black /path/to/directory

Scan the entire project in PyCharm

Black will recursively traverse the directory and format all Python files.

Format code snippets

black can also format code snippets using:

black -l 79 -

Then enter the code snippet you want to format and press Ctrl + D to end the input.

at last

Black is a popular Python code formatting tool that helps developers automatically format Python code to comply with the PEP 8 specification. By using Black, developers can reduce code review and discussion time and improve team collaboration efficiency. When using Black, you can combine version control, pay attention to formatting results, cooperate with editor plug-ins, and combine lint tools and other best practices to further improve the quality and maintainability of the code. Let's use Black together to make Python code more standardized and beautiful!

Reference documentation

https://en.wikipedia.org/wiki/Lint_(software)

GitHub - psf/black: The uncompromising Python code formatter

GitHub - psf/black: The uncompromising Python code formatter

https://black.readthedocs.io/en/stable/usage_and_configuration/index.html

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

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/132832266