black icon indicating copy to clipboard operation
black copied to clipboard

Don't break a line if it's too long because of comments

Open josephernest opened this issue 3 years ago • 5 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.

josephernest avatar Oct 12 '22 07:10 josephernest

Thanks @ichard26 for the tagging. Do you think there is already a setting for this?

josephernest avatar Oct 12 '22 12:10 josephernest

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.

e-gebes avatar Oct 12 '22 13:10 e-gebes

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.

ichard26 avatar Oct 12 '22 13:10 ichard26

Related: #1713.

TomFryers avatar Dec 06 '22 17:12 TomFryers

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 😅

felix-hilden avatar Jan 17 '23 21:01 felix-hilden

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.

JelleZijlstra avatar Apr 29 '23 01:04 JelleZijlstra