Whitespace and Blank Lines in Python: What PEP 8 Asks For

Whitespace is where most style warnings come from, and where a formatter saves the most review time. PEP 8 is precise about some spaces and deliberately flexible about others. Knowing which is which explains a few warnings that otherwise look arbitrary.
The "pet peeves"
PEP 8 groups the spaces it wants removed under the heading "Pet Peeves". Each has a matching pycodestyle code.
spam( ham[ 1 ], { 'eggs': 2 } ) # E201, E202
print(x , y) # E203
spam (1) # E211
dct ['key'] = lst [index] # E211
x = 1 # E221
long_variable = 3
spam(ham[1], {'eggs': 2})
print(x, y)
spam(1)
dct['key'] = lst[index]
x = 1
long_variable = 3
The last pair shows a habit many people bring from other languages: aligning a column of assignments with extra spaces. PEP 8 lists it as something to avoid, and pycodestyle reports E221 (multiple spaces before operator). Alignment looks tidy until one name changes length and every line in the block has to be touched, which also pollutes diffs.
PEP 8 also discourages a space between a trailing comma and a closing parenthesis, as in (0, ). pycodestyle does not flag that case, which is a reminder that the checker and the guide are not the same thing.
Around operators
PEP 8 asks for exactly one space on each side of assignment (=), augmented assignment (+=, -= and so on), comparisons (==, <, in, is not…) and Booleans (and, or, not). pycodestyle reports a missing space as E225.
For arithmetic it is more relaxed. When operators of different priorities appear together, you may leave out the spaces around the higher-priority ones so the grouping is visible. All of these are correct according to PEP 8:
i = i + 1
submitted += 1
x = x*2 - 1
hypot2 = x*x + y*y
c = (a+b) * (a-b)
Two constraints still apply: never more than one space, and always the same amount on both sides of a binary operator. Because spacing around arithmetic is a matter of judgment, pycodestyle's E226 (missing whitespace around arithmetic operator) is in its default ignore list. Formatters take a simpler line: black puts single spaces around most binary operators, while hugging the power operator when its operands are simple, as in x**2.
Commas, colons and slices
A comma, semicolon or colon should be followed by a space (E231 when it is not) and not preceded by one (E203). Slices are the exception that causes trouble. PEP 8 says that in a slice the colon "acts like a binary operator" and should have equal space on either side, so both of these are correct according to the guide:
ham[lower+offset:upper+offset]
ham[lower + offset : upper + offset]
pycodestyle, however, reports the second line as E203 (whitespace before ':'), because it cannot tell a slice colon from other colons in that check. Black formats complex slices exactly that way, which is why black's documentation recommends disabling E203 when you use flake8 or pycodestyle alongside it. If a linter and a formatter argue about a line, check PEP 8 before changing the code.
Keyword arguments, defaults and annotations
There are no spaces around = when it marks a keyword argument or the default value of an unannotated parameter (E251 if there are). Once a parameter has an annotation, the default gets spaces on both sides (E252 if it does not):
def complex_number(real, imag=0.0):
return complex(real=real, imag=imag)
def munge(sep: str = ",", limit=1000) -> str:
return sep * limit
Annotations follow the normal rules for colons, and the return arrow -> always has a space on each side.
Inline and block comments
An inline comment should be separated from the code by at least two spaces (E261) and start with # and a single space (E262). A block comment line also starts with # and a space (E265), unless it is indented text inside the comment. Paragraphs within a block comment are separated by a line containing a single #.
Blank lines
PEP 8's blank-line rules are short:
- Surround top-level function and class definitions with two blank lines.
- Surround method definitions inside a class with one blank line.
- Use extra blank lines sparingly to separate groups of related functions; they may be omitted between a set of related one-liners.
- Inside functions, use blank lines sparingly to mark logical sections.
pycodestyle turns these into precise checks: E302 (expected 2 blank lines before a top-level definition), E305 (expected 2 blank lines after one, before top-level code), E301 (a method with no blank line before it), E306 (a nested function with no blank line before it), E303 (too many blank lines: more than two anywhere, or two inside a function or class) and E304 (a blank line between a decorator and the function it decorates).
import math
def area(radius):
return math.pi * radius**2
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return area(self.radius)
print(Circle(2).area())
Comments do not count as code for these rules: a comment placed just before a function still needs the two blank lines above it, not between the comment and the def.
Invisible whitespace
Trailing spaces at the end of a line (W291), spaces on an otherwise blank line (W293) and blank lines at the end of the file (W391) are invisible in most editors, which is exactly the problem: PEP 8 notes that a backslash followed by a space and a newline does not count as a line continuation, and that many projects reject trailing whitespace in pre-commit hooks. The opposite problem, a file whose last line has no newline at all, is W292. Most editors can strip trailing whitespace and add the final newline on save.
Let the tools do it
Every rule in this article can be checked automatically, and most can be fixed automatically. The checker on our home page reports all the codes named above for a pasted snippet. For a project, a formatter (black, or ruff's formatter) settles spacing on every save, and a linter catches what the formatter leaves; see our reference to pycodestyle codes for the full list, and the indentation and line length guide for the layout rules that go with these.
Sources
- PEP 8, "Whitespace in Expressions and Statements", "Blank Lines" and "Comments".
- pycodestyle documentation, error codes E2, E3 and W2, and default ignore list (E226).
- Black documentation, "Using Black with other tools" (E203 and slices).
PEP 8, section by sectionIndentation and line length
Four spaces, no tabs, 79 characters: where these numbers come from, how to wrap long lines cleanly and which warnings point to each problem.
Linters & formatterspycodestyle error codes
What E225, E302, E501 or W291 actually mean and how to fix each one: a family-by-family reference to the codes used by pycodestyle, flake8 and ruff.
Linters & formattersBlack, the code formatter
88 characters, double quotes and the magic trailing comma: what Black changes, the few options it has, and how to make it agree with your linter.