black
black copied to clipboard
Don't break a line if it's too long because of comments
A long line is split into multiple lines if it exceeds the black_line_length setting.
How to not take the comments into consideration to compute the line length?
Example:
# this one should still be broken into multiple lines
long_function(param_1="this is a long line, longer than 80 characters", param_2="this is a long line, longer than 80 characters") # comment here
# this one SHOULD NOT be broken because the code is smaller than 80 char
short_function(param_1="foo", param_2="bar") # long comment here, which finally makes the line longer than 200 characters longer than 200 characters longer than 200 characters longer than 200 characters longer than 200 characters longer than 200 characters longer than 200 characters
Is there already a setting for this?
Currently the second example gives:
short_function(
param_1="foo", param_2="bar"
) # long comment here, which finally makes the line longer than 200 characters longer than 200 characters longer than 200 characters longer than 200 characters longer than 200 characters longer than 200 characters longer than 200 characters
and I'd prefer to not break the line at all.
Thanks @ichard26 for the tagging. Do you think there is already a setting for this?
I want to mention the special case of pragma comments that exceed the line length limit.
For pragmas of any kind # fmt: off, # pylint: disable=..., and so on, it might make sense to ignore those for computing the line length. Usually, they don't need to be read by humans anyway - it should be enough to see "ah that's the start of a pragma, I don't need to read further".
Moving pragmas to different lines might even break them from working, depending on the implementation of the tool.
There is not and I don't think we'll add one either since we try to avoid adding formatting configuration options. We can consider changing the logic in the presence of comments though.
Related: #1713.
This might be way too disruptive and I might not be considering it all the way through, but I'd prefer Black to move the comment on a different line before the line that would be too long. But likely too optimistic 😅
Black will continue to take comments into account while enforcing line length. Line length limits exist to make it easy to read code in environments with fixed-width lines, and code includes comments.