psf / black

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

Long lines that concatenate list comprehensions #4353

Open tomkcook opened 1 month ago

tomkcook commented 1 month ago

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 commented 1 month ago

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]
    )
AMK9978 commented 1 month ago

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

JelleZijlstra commented 1 month ago

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.