2.2. Horizontal Spacing

Empty space is just as important for readability as the code you write. These spaces help separate distinct parts of code from each other, making them easier to identify. This section explains horizontal spacing — that is, the placement of blank space within a single line of code, including the indentationat the front of the line.

2.2.1. Use Space Characters for Indentation

Indentation is the whitespace at the beginning of a code line. You can use one of two whitespace characters, a space or a tab, to indent your code. Although either character works, the best practice is to use spaces instead of tabs for indentation.

The reason is that these two characters behave differently. A space character is always rendered on the screen as a string value with a single space, like this ' ' . But a tab character, which is rendered as a string value containing an escape character, or '\t' , is more ambiguous. Tabs often, but not always, render as a variable amount of spacing so the following text begins at the next tab stop. The tab stop are positioned every eight spaces across the width of a text file. You can see this variation in the following interactive shell example, which first separates words with space characters and then with tab characters:

>>> print('Hello there, friend!\nHow are you?')
Hello there, friend!
How are you?
>>> print('Hello\tthere,\tfriend!\nHow\tare\tyou?')
Hello       there,  friend!
How are     you?

Because tabs represent a varying width of whitespace, you should avoid using them in your source code. Most code editors and IDEs will automati- cally insert four or eight space characters when you press the TAB key instead of one tab character.

You also can’t use tabs and spaces for indentation in the same block of code. Using both for indentation was such a source of tedious bugs in ear- lier Python programs that Python 3 won’t even run code indented like this; it raises a TabError: inconsistent use of tabs and spaces in indentation excep- tion instead. Black automatically converts any tab characters you use for indentation into four space characters.

As for the length of each indentation level, the common practice in Python code is four spaces per level of indentation. The space characters in the following example have been marked with periods to make them visible:

def getCatAmount(): ....numCats = input('How many cats do you have?') ....if int(numCats) < 6: ........print('You should get more cats.')

The four-space standard has practical benefits compared to the alter- natives; using eight spaces per level of indentation results in code that quickly runs up against line length limits, whereas using two space charac- ters per level of indentation can make the differences in indentation hard to see. Programmers often don’t consider other amounts, such as three or six spaces, because they, and binary computing in general, have a bias for numbers that are powers of two: 2, 4, 8, 16, and so on. ## Spacing Within a Line Horizontal spacing has more to it than just the indentation. Spaces are important for making different parts of a code line appear visually distinct. If you never use space characters, your line can end up dense and hard to parse. The following subsections provide some spacing rules to follow. ### Put a Single Space Between Operators and Identifiers If you don’t leave spaces between operators and identifiers, your code will appear to run together. For example, this line has spaces separating opera- tors and variables:

YES: blanks = blanks[:i] + secretWord[i] + blanks[i + 1 :]

This line removes all spacing:

NO:blanks=blanks[:i]+secretWord[i]+blanks[i+1:]

In both cases, the code uses the + operator to add three values, but with- out spacing, the + in blanks[i+1:] can appear to be adding a fourth value. The spaces make it more obvious that this + is part of a slice for the value in blanks .

Put No Spaces Before Separators and a Single Space After Separators

We separate the items lists and dictionaries, as well as the parameters in function def statements, using comma characters. You should place no spaces before these commas and a single space after them, as in this example:

YES: def spam(eggs, bacon, ham): YES: weights = [42.0, 3.1415, 2.718]

Otherwise, you’ll end up with “bunched up” code that is harder to read:

NO: def spam(eggs,bacon,ham): NO: weights = [42.0,3.1415,2.718]

Don’t add spaces before the separator, because that unnecessarily draws the eye to the separator character:

NO: def spam(eggs , bacon , ham): NO: weights = [42.0 , 3.1415 , 2.718]

Black automatically inserts a space after commas and removes spaces before them.

Don’t Put Spaces Before or After Periods

Python allows you to insert spaces before and after the periods marking the beginning of a Python attribute, but you should avoid doing so. By not plac- ing spaces there, you emphasize the connection between the object and its attribute, as in this example:

YES: 'Hello, world'.upper()

If you put spaces before or after the period, the object and attribute look like they’re unrelated to each other:

NO: 'Hello, world' . upper()

Black automatically removes spaces surrounding periods. ### Don’t Put Spaces After a Function, Method, or Container Name We can readily identify function and method names because they’re fol- lowed by a set of parentheses, so don’t put a space between the name and the opening parenthesis. We would normally write a function call like this:

YES: print('Hello, world!')

But adding a space makes this singular function call look like it’s two separate things:

NO: print ('Hello, world!')

Black removes any spaces between a function or method name and its opening parenthesis.

Similarly, don’t put spaces before the opening square bracket for an index, slice, or key. We normally access items inside a container type (such as a list, dictionary, or tuple) without adding spaces between the variable name and opening square bracket, like this:

YES: spam[2] YES: spam[0:3] YES: pet['name']

Adding a space once again makes the code look like two separate things:

NO: spam [2] NO: spam [0:3] NO: pet ['name']

Black removes any spaces between the variable name and opening square bracket.

Don’t Put Spaces After Opening Brackets or Before Closing Brackets

There should be no spaces separating parentheses, square brackets, or braces and their contents. For example, the parameters in a def statement or values in a list should start and end immediately after and before their parentheses and square brackets:

YES: def spam(eggs, bacon, ham): YES: weights = [42.0, 3.1415, 2.718]

You should not put a space after an opening or before a closing paren- theses or square brackets:

NO: def spam( eggs, bacon, ham ): NO: weights = [ 42.0, 3.1415, 2.718 ]

Adding these spaces doesn’t improve the code’s readability, so it’s unnecessary. Black removes these spaces if they exist in your code. ### Put Two Spaces Before End-of-Line Comments If you add comments to the end of a code line, put two spaces after the end of the code and before the # character that begins the comment:

YES: print('Hello, world!') # Display a greeting.

The two spaces make it easier to distinguish the code from the comment. A single space, or worse, no space, makes it more difficult to notice this separation:

NO: print('Hello, world!') # Display a greeting. NO: print('Hello, world!')# Display a greeting.

Black puts two spaces between the end of the code and the start of the comment.

In general, I advise against putting comments at the end of a code line, because they can make the line too lengthy to read onscreen.