Black formatter - Ignore specific multi-line code

You can use #fmt: on/off as explained in the issue linked. In your case 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 formatting is activated again with # fmt: on


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!


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)