Black: Inline comments can make ugly formatting for actual code

Created on 1 Nov 2018  路  4Comments  路  Source: psf/black

Black https://github.com/ambv/black/commit/32eed7

Playground link

Options

--line-length=60
--py36

Input

if now.second < 30:  # Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    continue

Output

if (
    now.second < 30
):  # Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    continue

Expected

The code should not be changed, especially not to this ugly form, based on how long a comment is afterwards.

comments wontfix

Most helpful comment

I agree that the generated code looks bad.

What are thoughts on moving inline comment that exceed the line-length to the proceeding line?

# Lorem ipsum dolor sit amet, consectetur adipiscing elit.
if now.second < 30:
    continue

All 4 comments

I agree that the generated code looks bad.

What are thoughts on moving inline comment that exceed the line-length to the proceeding line?

# Lorem ipsum dolor sit amet, consectetur adipiscing elit.
if now.second < 30:
    continue

Black made those gymnastics with the parentheses and the comment because the comment was too long. Black cannot move that up on its own as it changes the position of the comment relative to content and it might change meaning of what we're looking at. More importantly, in the general case it might not be as simple as moving "one line up".

The solution is for you to manually move the comment up and reformat.

This is contrary to how ignores in flake8 work, and I would rather it leave the line alone than change a single line to multiline with the comment at the end if the goal is to be safe.

The goal for this tool is to reformat code so that it fits the line length limit while still executing the same. It's concerned with safety in this regard alone. "To be safe" is vague and subjective otherwise.

What Black does in this case is simple: the inline comment was originally put after the colon token and it stays after the colon token. I don't think it's a terrible choice but agreed, this does interfere with pragma-style comments and we'll be addressing some of that in #379.

Was this page helpful?
0 / 5 - 0 ratings