How to format mathematical expressions?

Since the issue linked by @tupui above (Allow no space between operator ** · Issue #538 · psf/black · GitHub), black’s formatting is better for the ** operator. It currently produces this:

i = i + 1
submitted += 1
x = x * 2 - 1
hypot2 = x * x + y * y
c = (a + b) * (a - b)
dfdx = sign * (-2 * x + 2 * y + 2)
result = 2 * x**2 + 3 * x ** (2 / 3)
y = 4 * x**2 + 2 * x + 1
c_i1j = (
    1.0
    / n**2.0
    * np.prod(
        0.5 * (2.0 + abs(z_ij[i1, :]) + abs(z_ij) - abs(z_ij[i1, :] - z_ij)), axis=1
    )
)

So the remaining points of contention from the original issue are:

  1. If operators with different priorities are used, add whitespace around the operators with the lowest priority(ies).
  2. There is no space before and after operators *,/. Only exception is if the expression consist of a single operator linking two groups.
  3. When splitting an equation, new lines should start with the operator linking the previous and next logical block. Single digit, brackets on a line are forbidden. Use the available horizontal space as much as possible.

Could items 1 & 2 be summarized as “Remove spacing between * or / and ‘simple’ operands if there are higher priority operators (+, -) in the expression”?

Assuming that “simple” operand is defined the same was as it is in the ** spacing issue:

an operand is considered “simple” if it’s only a NAME, numeric CONSTANT, or attribute access (chained attribute access is allowed), with or without a preceding unary operator.

Though whether this is beneficial enough to be worth consideration is debatable, as mentioned by Stefan.

Regarding issue 3, I would suggest instead deferring to the return & indent style that black currently uses, but with attempting to keep numerical expressions within one line. Something like this:

c_i1j = 1.0 / n**2.0 * np.prod(
        0.5 * (2.0 + abs(z_ij[i1, :]) + abs(z_ij) - abs(z_ij[i1, :] - z_ij)),
        axis=1
    )

The main reasons for this are just consistency with the existing black format, and avoiding a lot of lost whitespace when an align point is in the middle of the screen.