black#

Black is the most widely used Python code formatter and backed by the Python Software Foundation.

Motivation#

Not only can the same problem be solved by different code implementations, but the same code can also be formatted differently. Even though the following snippet

a=  [ 1,2
,3]
print(
a  )

is perfectly valid to the Python interpreter, adapting the white space and newlines

a = [1, 2, 3]
print(a)

makes it much more readable to the human mind. Granted that this example is a bit extreme, but the details of where to put commas, parentheses, whitespace and newlines are often a matter of taste, or even better, convention. The Python community introduced PEP 8 as a “Style Guide for Python Code”. Adhering to a common coding style facilitates writing new code, as well as reading existing code.

Using a code formatter like black goes even a step further, as it will automatically format the code for you. No matter what the code looks like at first, the formatter will always make it look exactly the same and adhere to the Black code style.

By using Black, you agree to cede control over minutiae of hand-formatting. In return, Black gives you speed, determinism, and freedom […] You will save time and mental energy for more important matters.

[…] Blackened code looks the same regardless of the project you’re reading. Formatting becomes transparent after a while and you can focus on the content instead.

[source]

Usage#

Python source code can be formatted by invoking black on a single file

$ black some_file.py

or a whole folder, for instance the current directory

$ black .

On some projects you may need to increase the maximum line length (from its default of 88 characters)

$ black -l 100 .

Please refer to the official documentation for all usage and configuration options.

Instead of the manual invocation on the command line, the code formatter can also be integrated in various editors to automatically format the file on each save, or as a hook in your git repository. For instance in VSCode you can adapt your project’s settings.json to include

"python.formatting.provider": "black",
"python.formatting.blackArgs": [
	"--line-length=100"
],
"[python]": {
	"editor.formatOnSave": true
},