Pythonic way to split math calculations

Viewed 9988

I use the ninja-ide and I find amazing the way it can complain about everything (yellow undertext line everywhere) because I think its a way to improve my coding to make it more standard.

However, since it does also complain about the length of the line of code (which of course makes a lot of sense, since no one likes to scroll horizontally to read the code), I've got stuck to this problem.

Lets say this line:

 v1, v2 = np.sum(((b1 - m1) ** 2) * p1) / q1, np.sum(((b2 - m2) ** 2) * p2) / q2

It does have 81 characters including the spaces, in this case I could split it like this:

    v1 = np.sum(((b1 - m1) ** 2) * p1) / q1
    v2 = np.sum(((b2 - m2) ** 2) * p2) / q2

But that doesn't feel much pythonic and there is also another problem:

What if there wasn't the comma? I mean how could I split something like this:

   v2 = np.sum(((b1 - m1) ** 2 * np.sum(((b2 - np.sum(((b2 - m2) ** 2) * p2) / q2) ** 2) * p2) / q2) * p1) 

This above doesn't have any sense mathematically wise, it's just to explain what I meant.

2 Answers

A backslash can be used to split long lines.

Where you split it is up to you, but the above line could be reworked as such:

v2 = np.sum(((b1 - m1) ** 2 * \
        np.sum(((b2 - np.sum(((b2 - m2) ** 2) * p2) / q2) ** 2) * p2) \
                                                                / q2) * p1)

I'd first try to reduce the code some other way (e.g. renaming variables, using other modules, altering the order of operations).


@user2357112 correctly notes that you don't need the backslash when splitting code inside unmatched parentheses, brackets, or braces, so the above code could also look like this:

v2 = np.sum(((b1 - m1) ** 2 *
        np.sum(((b2 - np.sum(((b2 - m2) ** 2) * p2) / q2) ** 2) * p2)
                                                                / q2) * p1)

From PEP 8's Maximum Line Length:

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.

Don't bother about pythonic-way. Bother about good reading, performance and extensibility of your code. I think below would good 'pythonic' :) solution:

formula = lambda b, m, p, q: np.sum(((b - m) ** 2) * p) / q
v1, v2 = formula(b1, m1, p1, q1), formula(b2, m2, p2, q2)

Advantage of this way is you can use formula many times. And you get shortest string.

Related