Black formatter - Ignore specific multi-line code
PythonCode FormattingPython BlackPython Problem Overview
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?
Python Solutions
Solution 1 - Python
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
Solution 2 - Python
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!
Solution 3 - Python
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)