2.4. Black: The Uncompromising Code Formatter¶
Black automatically formats the code inside your .py files. Although you should understand the formatting rules covered in this chapter, Black can do all the actual styling for you. If you’re working on a coding project with others, you can instantly settle many arguments on how to format code by just letting Black decide.
You can’t change many of the rules that Black follows, which is why it’s described as “the uncompromising code formatter.” Indeed, the tool’s name comes from Henry Ford’s quote about the automobile colors choices he offered his customers: “You can have any color you want, as long as it’s black.”
I’ve just described the exact styles that Black uses; you can find Black’s full style guide at https://black.readthedocs.io/en/stable/the_black_code_style.html. ## Installing Black Install Black using the pip tool that comes with Python. In Windows, do this by opening a Command Prompt window and entering the following:
C:UsersAl>python -m pip install --user black
On macOS and Linux, open a Terminal window and enter python3 rather than python (you should do this for all the instructions in this book that use python ):
Als-MacBook-Pro:~ al$ python3 -m pip install --user black
The -m option tells Python to run the pip module as an application, which some Python modules are set up to do. Test that the installation was successful by running python -m black . You should see the message No paths given. Nothing to do. rather than No module named black. ## Running Black from the Command Line You can run Black for any Python file from the Command Prompt or Terminal window. In addition, your IDE or code editor can run Black in the background. You’ll find instructions for getting Black to work with Jupyter Notebook, Visual Studio Code, PyCharm, and other editors on Black’s home page at https://github.com/psf/black/.
Let’s say that you want to format a file called yourScript.py automatically. From the command line in Windows, run the following (on macOS and Linux, use the python3 command instead of python ):
C:UsersAl>python -m black yourScript.py
After you run this command, the content of yourScript.py will be format- ted according to Black’s style guide.
Your PATH environment variable might already be set up to run Black directly, in which case you can format yourScript.py by simply entering the following:
C:UsersAl>black yourScript.py
If you want to run Black over every .py file in a folder, specify a single folder instead of an individual file. The following Windows example for- mats every file in the C::raw-latex:`yourPythonFiles `folder, including its subfolders:
C:UsersAl>python -m black C:yourPythonFiles
Specifying the folder is useful if your project contains several Python files and you don’t want to enter a command for each one.
Although Black is fairly strict about how it formats code, the next three subsections describe a few options that you can change. To see the full range of options that Black offers, run python -m black –help .
2.4.1. Adjusting Black’s Line Length Setting¶
The standard line of Python code is 80 characters long. The history of the 80 character line dates back to the era of punch card computing in the 1920s when IBM introduced punch cards that had 80 columns and 12 rows. The 80 column standard remained for the printers, monitors, and com- mand line windows developed over the next several decades.
But in the 21st century, high-resolution screens can display text that is more than 80 characters wide. A longer line length can keep you from having to scroll vertically to view a file. A shorter line length can keep too much code from crowding on a single line and allow you to compare two source code files side by side without having to scroll horizontally.
Black uses a default of 88 characters per line for the rather arbitrary reason that it is 10 percent more than the standard 80 character line. My preference is to use 120 characters. To tell Black to format your code with, for example, a 120-character line length limit, use the -l 120 (that’s the low- ercase letter L, not the number 1) command line option. On Windows, the command looks like this:
C:UsersAl>python -m black -l 120 yourScript.py
No matter what line length limit you choose for your project, all .py files in a project should use the same limit. ### Disabling Black’s Double-Quoted Strings Setting Black automatically changes any string literals in your code from using single quotes to double quotes unless the string contains double quote char- acters, in which case it uses single quotes. For example, let’s say yourScript.py contains the following:
>>> a='Hello'
>>> b="Hello"
>>> c='Al\'s cat, Zophie.'
>>> d='Zophie said, "Meow"'
>>> e="Zophie said, \"Meow\""
>>> f='''Hello'''
Running Black on yourScript.py would format it like this:
>>> a="Hello"
>>> b="Hello"
>>> c="Al's cat, Zophie."
>>> d='Zophie said, "Meow"'
>>> e='Zophie said, "Meow"'
>>> f="""Hello"""
Black’s preference for double quotes makes your Python code look simi- lar to code written in other programming languages, which often use dou- ble quotes for string literals. Notice that the strings for variables a , b , and c use double quotes. The string for variable d retains its original single quotes to avoid escaping any double quotes within the string 2. Note that Black also uses double quotes for Python’s triple-quoted, multiline strings 3.
But if you want Black to leave your string literals as you wrote them and not change the type of quotes used, pass it the -S command line option. (Note that the S is uppercase.) For example, running Black on the original yourScript.py file in Windows would produce the following output:
C:UsersAl>python –m black -S yourScript.py All done! 1 file left unchanged.
You can also use the -l line length limit and -S options in the same command:
C:UsersAl>python –m black –l 120 -S yourScript.py
2.4.2. Previewing the Changes Black Will Make¶
Although Black won’t rename your variable or change your program’s behavior, you might not like the style changes Black makes. If you want to stick to your original formatting, you could either use version control for your source code or maintain your own backups. Alternatively, you can preview the changes Black would make without letting it actually alter your files by running Black with the –diff command line option. In Windows, it looks like this:
C:UsersAl>python -m black --diff yourScript.py
This command outputs the differences in the diff format commonly used by version control software, but it’s generally readable by humans. For example, if yourScript.py contains the line weights=[42.0,3.1415,2.718] , run- ning the –diff option would display this result:
C:UsersAl>python -m black --diff yourScript.py --- yourScript.py 2020-12-07 02:04:23.141417 +0000
+++ yourScript.py 2020-12-07 02:08:13.893578 +0000 @@ -1 +1,2 @@ -weights=[42.0,3.1415,2.718] +weights = [42.0, 3.1415, 2.718]
The minus sign indicates that Black would remove the line weights= [42.0,3.1415,2.718] and replace it with the line prefixed with a plus sign: weights = [42.0, 3.1415, 2.718] . Keep in mind that once you’ve run Black to change your source code files, there’s no way to undo this change. You need to either make backup copies of your source code or use version control software, such as Git, before running Black.
Disabling Black for Parts of Your Code¶
As great as Black is, you might not want it to format some sections of your code. For example, I like to do my own special spacing whenever I’m lining up multiple related assignment statements, as in the following example:

Black would remove the additional spaces before the = assignment oper- ator, making them, in my opinion, less readable:

By adding # fmt: off and # fmt: on comments, we can tell Black to turn off its code formatting for these lines and then resume code formatting afterward:

Running Black on this file now won’t affect the unique spacing, or any other formatting, in the code between these two comments.
2.5. Summary¶
Although good formatting can be invisible, poor formatting can make read- ing code frustrating. Style is subjective, but the software development field generally agrees on what constitutes good and poor formatting while still leaving room for personal preferences.
Python’s syntax makes it rather flexible when it comes to style. If you’re writing code that nobody else will ever see, you can write it however you like. But much of software development is collaborative. Whether you’re working with others on a project or simply want to ask more experienced developers to review your work, formatting your code to fit accepted style guides is important.
Formatting your code in an editor is a boring task that you can auto- mate with a tool like Black. This chapter covered several of the guidelines that Black follows to make your code more readable, including spacing code vertically and horizontally, which keeps it from being too dense to read eas- ily, and setting a limit on how long each line should be. Black enforces these rules for you, preventing potential style arguments with collaborators.
But there’s more to code style than spacing and deciding between single and double quotes. For instance, choosing descriptive variable names is also a critical factor for code readability. Although automated tools like Black can make syntactic decisions, such as the amount of spacing code should have, they can’t make semantic decisions, such as what a good variable name is. That responsibility is yours, and we’ll discuss this topic in the next chapter.