Does PEP 8 require whitespace around operators in function arguments?

Your Vim plugin was wrong when you asked in 2013… but right in 2010, when it was authored. PEP 8 has changed on several occasions, and the answer to your question has changed as well.

Originally, PEP 8 contained the phrase:

Use spaces around arithmetic operators

Under that rule,

range(a, b+1)

is unambiguously wrong and should be written as

range(a, b + 1)

That is the rule that pycodestyle (the Python linter, previously known as, that the asker’s Vim plugin uses under the hood) implemented for several years.

However, this was changed in April 2012. The straightforward language that left no room for discretion was replaced with this much woollier advice:

If operators with different priorities are used, consider adding whitespace around the operators with the lowest priority(ies). Use your own judgment; however, never use more than one space, and always have the same amount of whitespace on both sides of a binary operator.

Confusingly, the examples that illustrate this rule were originally left unchanged (and hence in contradiction to the prose). This was eventually fixed, but not very well, and the examples remain confusing, seeming to imply a much stricter and less subjective rule than the prose does.

There is still a rule requiring whitespace around some particular operators:

Always surround these binary operators with a single space on either side: assignment ( = ), augmented assignment ( += , -= etc.), comparisons ( == , < , > , != , <> , <= , >= , in , not in , is , is not ), Booleans ( and , or , not ).

but note that this rule is explicit about which operators it refers to and arithmetic operators like + are not in the list.

Thus the PEP, in its current form, does not dictate whether or not you should use spaces around the + operator (or other arithmetic operators like * and / and **). You are free to “use your own judgement”.

By the way, the pycodestyle linter changed its behaviour in late 2012 to reflect the change in the PEP, separating the rules about using whitespace around operators into two error codes, E225 (for failure to use whitespace around the operators that PEP 8 still requires whitespace around), which is on by default, and E226 (for failure to use whitespace around arithmetic operators), which is ignored by default. The question asker here must’ve been using a slightly outdated version of the linter when he asked this question in 2013, given the error that he saw.

Leave a Comment