Black formatter – Ignore specific multi-line code

Question:

I would like to ignore a specific multi-line code by black python formatter. Particularly, this is used for np.array or matrix construction which turned ugly when formatted. Below is the example.

np.array(
    [
        [1, 0, 0, 0],
        [0, -1, 0, 0],
        [0, 0, 1, 0],
        [0, 0, 0, -1],
    ]
)
# Will be formatted to
np.array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -1]])

I found this issue in black github, but that only works for inline command, which is not what I have here.

Is there anything I can do to achieve this for a multi-line code?

Asked By: Darren Christopher

||

Answers:

You can use #fmt: on/off (docs) as explained in the issue linked. Here, it would look like:

# fmt: off
np.array(
    [
        [1, 0, 0, 0],
        [0, -1, 0, 0],
        [0, 0, 1, 0],
        [0, 0, 0, -1],
    ]
)
# fmt: on

# fmt: off disables formatting for all following lines until re-activated with # fmt: on.

Answered By: OriolAbril

If you’re willing to change your code slightly, then Black leaves either of the following alone:

contents = [
    [1, 0, 0, 0],
    [0, -1, 0, 0],
    [0, 0, 1, 0],
    [0, 0, 0, -1],
]

np.array(contents)

This is because the trailing comma in the multi-line list is magic. Black takes it to mean that you plan to extend the list in future, although in this case it just means Black’s style isn’t very readable. Unfortunately the trailing comma isn’t magic enough to work when the list is wrapped in that extra function call.

np.array(
    [
        # just say anything
        [1, 0, 0, 0],
        [0, -1, 0, 0],
        [0, 0, 1, 0],
        [0, 0, 0, -1],
    ]
)

This is because Black cannot outwit Python’s lack of inline comments!

Answered By: Steve Jessop

The latest version of black ( >= 21.0) takes into account the comma after the last element.

So:

np.array(
    [
        [1, 0, 0, 0],
        [0, -1, 0, 0],
        [0, 0, 1, 0],
        [0, 0, 0, -1]
    ]
)

will be formatted to:

np.array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -1]])

(note no last comma)

Instead

np.array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -1],])

will be formatted to:

np.array(
    [
        [1, 0, 0, 0],
        [0, -1, 0, 0],
        [0, 0, 1, 0],
        [0, 0, 0, -1],
    ]
)

(note last comma)

Answered By: SeF