pythoncode-formattingpython-black

Black formatter - Ignore specific multi-line code


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?


Solution

  • 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.