Skip to content
Advertisement

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?

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement