psf / black

The uncompromising Python code formatter
https://black.readthedocs.io/en/stable/
MIT License
38.7k stars 2.43k forks source link

Prefere linebreaks on binary operators over linebreaks at function parentheses #1254

Open MarkusPiotrowski opened 4 years ago

MarkusPiotrowski commented 4 years ago

This is similar to other issues like #571, #587, #1050 and #1094.

Black should prefer line-breaking at binary operators over function parentheses or index/slice parentheses of one of the expression's elements. Especially in multi-element expression (e.g. calculations), the code becomes hard to read.

I have even seen worse examples than the two below, where a calculation becomes impossible to follow. But I think these two examples are quite clear.

Examples in the current Black style

# Example 1
            nogap_score = score_matrix[row - 1][col - 1] + match_fn(
               sequenceA[row - 1], sequenceB[col - 1]
            )

# Example 2
            ali_seqB = (row_distance - col_distance) * gap_char + sequenceB[
                lenB - 1 : col - 1 : -1
            ]

Desired style How do you think Black should format the above snippets:

# Example 1
            nogap_score = (
                score_matrix[row - 1][col - 1]
                + match_fn(sequenceA[row - 1], sequenceB[col - 1]
            )

# Example 2
            ali_seqB = (
                (row_distance - col_distance) * gap_char
                + sequenceB[lenB - 1 : col - 1 : -1 ]
             )
ambv commented 4 years ago

Both of your examples increase vertical space use. Black prefers to split by operator if there's more than one, otherwise it leads to a myriad of pathological cases. We've tried always splitting on operators, it's less code actually. But testing with large bodies of source code, this wound up being worse on average.

I'm not closing this yet as I do feel we have tackle this somehow.

felix-hilden commented 2 years ago

Very much related to #2156 as well.