Use of Black — code formatter
Writing well-formatted code is very important, small programs are easy to understand but as programs get complex they get harder and harder to understand. At some point, you can’t even understand the code written by you. To avoid this, it is needed to write code in a readable format. Here Black comes into play, Black ensures code quality.
What is Black?
Linters such as pycodestyle or flake8 show whether your code is according to PEP8 format, which is the official Python style guide. But the problem is that it gives a burden to the developers to fix this formatting style. Here Black comes into play not only does it report format errors but also fixes them.
Black is the uncompromising Python code formatter. By using it, you agree to cede control over minutiae of hand-formatting. In return, Black gives you speed, determinism, and freedom from pycodestyle nagging about formatting. You will save time and mental energy for more important matters.
Note: Black can be easily integrated with many editors such as Vim, Emacs, VSCode, Atom or a version control system like GIT.
Installing and using Black :
Black requires Python 3.6.0+ with pip installed :
$ pip install black
It is very simple to use black. Run the below command in the terminal.
$ black [file or directory]
This will reformat your code using the Black codestyle.
Example 1:Let’s create an unformatted file name “sample.py” and we want to format it using black. Below is the implementation.
After creating this file run the below command.
Output file:
In the above example, both are the same piece code but after using black it is formatted and thus easy to understand.