Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Line unnecessarily expanded

Tags:

python

ruff

In my Python code I have a line that looks like so:

tm = tm[0:3] + [0,] + tm[3:6] + [0,]

Ruff attempts to fix this with the following 10 lines, which are arguably less legible:

tm = (
    tm[0:3]
    + [
        0,
    ]
    + tm[3:6]
    + [
        0,
    ]
)

Why is Ruff expanding the statement? Is there a way to disable this behaviour?

like image 617
Besi Avatar asked Oct 31 '25 02:10

Besi


1 Answers

tm = (
    tm[0:3]
    + [
        0,  # <---
    ]
    + tm[3:6]
    + [
        0,  # <---
    ]
)

Both of those "<---" lines end with what ruff calls "the magic comma". It is an explicit request to please use multi-line formatting.

A more obvious example might look like

    + [
        1,
        2,
        3,  # <---
    ]

where the final , comma after 3 is the one that asks for single element per line.

Remove that optional comma, and both ruff and black will revert to a more compact notation.

benefit

In many source files it's a big advantage to request such formatting, as it minimizes diffs. Some non-python languages, such as SQL, prohibit a trailing , comma. This leads to needlessly verbose diffs, which show that final line was "3" (no comma), and in the edited version we have "3," and a new final line of "4" (no comma). Inevitably "5" is added, requiring us to dirty the "4" line to add a comma.

Occasionally you may see some craziness like this, which is a very painful way to improve the accuracy of git annotate foo.sql output.

SELECT
    a
  , b
  , c
FROM some_table ...
like image 74
J_H Avatar answered Nov 02 '25 17:11

J_H