Skip to content

Enforced Spacing Around the Binary Operators #3530

@gokberkgunes

Description

@gokberkgunes

Problem Statement

When binary operators, such as +, -, *, /, %, are used, their priority is given to them, and spacing should be set by their priorities. The stress could be seen when people write multiplication operators with some constants; they generally tend to drop the operator and write them together, e.g., 2*x becomes 2x.

Similarly, not just general logic but also PEP8 suggests following this priority style. However, Black does not recognize the prioritization of binary operators. Moreover, Black tries to style the code wrongly by force padding the binary operators with spaces around them.

PEP8 Recommendation

Below, you may see the excerpt from PEP8,

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:

# Correct:
i = i + 1
submitted += 1
x = x*2 - 1
hypot2 = x*x + y*y
c = (a+b) * (a-b)
# Wrong:
i=i+1
submitted +=1
x = x * 2 - 1
hypot2 = x * x + y * y
c = (a + b) * (a - b)

Examples on Black Formatting

As examples given below, it may be argued that adding a padding around every operator with a single operator is decreasing readability of the problem. Again, noting that this behavior appears to be enforced on the user.

(a+b) * (a-b) ---> (a + b) * (a - b)
a*b + b*a     ---> a * b + b * a
2*(a*b) + b*d ---> 2 * (a * b) + b * d

Possible Remedies to the Problem

  • Removal of force formatting the binary operators. Either give the user freedom to stop formatting binary operators automatically or, with changed default, introduce an option to add spacing around operators.
  • Implementation of a priority formatting option that recognizes parenthesis and operator importance.

Metadata

Metadata

Assignees

No one assigned

    Labels

    T: styleWhat do we want Blackened code to look like?

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions