Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What motivates the "no-alignment" policy of PEP 8?

Tags:

python

pep8

pep

PEP 8 has a specific guideline against whitespace around operators for alignment:

No:

x             = 1
y             = 2
long_variable = 3

If I understand correctly, the following is also recommended against:

salaries = {
    "Alice": 1500,
    "Bob":   1300,
    #      ^^ extra whitespace
}

What are these specific recommendations useful for?

like image 569
Alexis Avatar asked Dec 30 '25 05:12

Alexis


1 Answers

This rule was part of Guido’s original style essay published in 1998, where he states:

(Don't bother to argue with me on any of the above -- I've grown accustomed to this style over 15 years.)

So he didn’t directly motivate this one, but I can think of a few good reasons why you’d want to avoid doing this. Aligning code with spaces may seem like a good idea at the time, everything lining up neatly.

But most projects are not static. You often see that in real-life projects code is changed over time, and you may add or remove or rename entries in the list you so carefully aligned. You could easily end up with having to adjust the alignment of the whole block, because your change altered what is now the longest entry.

Such changes now cause you more work. You have to re-align the block. Your colleagues and your future self have to do more work reading the changeset in your version control system.

(And yes, a code formatter can do the re-aligning, but automated tools can't fix your code diff now touching a large number of lines that had _nothing to do with your commit other than being re-aligned).

Or, a later editor may balk at the prospect of having to re-align additional entries. The Wine project dlls/msi/msipriv.h file started nicely aligned, but over time inconsistencies creep in and you end up with a bit of a mess.

Next, the alignment doesn't necessarily make code easier to read; with enough white-space in between, you can easily end up misreading what value goes with what name.

At the same time, PEP 8 is a guideline. The document itself states:

A Foolish Consistency is the Hobgoblin of Little Minds

[...]

However, know when to be inconsistent -- sometimes style guide recommendations just aren't applicable. When in doubt, use your best judgment. Look at other examples and decide what looks best.

You need to make your own decisions as to when to use alignment anyway.

Some parts of the Python standard library break this specific rule (and yes, that's a Python reflection of the Wine project example above; that example was imported from an external project years ago), and there are other examples of broken PEP8 rules there for historical reasons, but sometimes in some, limited areas, breaking the rules can make sense.

like image 67
Martijn Pieters Avatar answered Dec 31 '25 19:12

Martijn Pieters