black icon indicating copy to clipboard operation
black copied to clipboard

Long lines that concatenate list comprehensions

Open tomkcook opened this issue 1 year ago • 3 comments

Describe the style change

Concatenated list comprehensions should be put one-per-line rather than splitting within a comprehension.

Examples in the current Black style

            matching_routes = [r for r in routes if r.get("dst") and ip in ipaddress.ip_network(r.get("dst"))] + [
                r for r in routes if r.get("dst") == "" and r.get("family") == family
            ]

Desired style

            matching_routes = (
                [r for r in routes if r.get("dst") and ip in ipaddress.ip_network(r.get("dst"))] +
                [r for r in routes if r.get("dst") == "" and r.get("family") == family]
            )

Additional context

Currently, Black will reformat the desired style above into the current style shown above, which is a pretty clear loss for readability. Note that the above example was done with a custom line length limit of 120 but the same issue will come up with other line lengths.

tomkcook avatar May 08 '24 14:05 tomkcook

A complete example:

def foo():
    matching_routes = [
        r for r in routes if r.get("dst") and ip in ipaddress.ip_network(r.get("dst"))
    ] + [r for r in routes if r.get("dst") == "" and r.get("family") == family]

would be better as:

def foo():
    matching_routes = (
        [r for r in routes if r.get("dst") and ip in ipaddress.ip_network(r.get("dst"))] +
        [r for r in routes if r.get("dst") == "" and r.get("family") == family]
    )

tomkcook avatar May 08 '24 14:05 tomkcook

Hey Guys! @JelleZijlstra Is this accepted? I agree with @tomkcook that his proposal is more beautiful. I'd like to work on this!

amk9978 avatar May 16 '24 13:05 amk9978

I agree it looks better in these examples and I'd encourage you to make a PR trying to implement it, but style changes in Black often have effects in unexpected areas, and I'll have to see the changes from the PR before I can commit to making a style change.

JelleZijlstra avatar May 16 '24 15:05 JelleZijlstra