Skip to content

Black 22.1.0 strips some comments #2873

@henryiii

Description

@henryiii

Describe the bug

Black will now occasionally strip comments (including type: ignore comments).

To Reproduce

For example, take this code:

if hasattr(view, "sum_of_weights"):
    return np.divide(  # type: ignore[no-any-return]
        view.variance,  # type: ignore[union-attr]
        view.sum_of_weights,  # type: ignore[union-attr]
        out=np.full(view.sum_of_weights.shape, np.nan),  # type: ignore[union-attr]
        where=view.sum_of_weights > 1,  # type: ignore[union-attr]
        where=view.sum_of_weights**2 > view.sum_of_weights_squared,  # type: ignore[union-attr]
    )

And run it with these arguments:

$ black file.py

The resulting Python code is:

if hasattr(view, "sum_of_weights"):
    return np.divide(  # type: ignore[no-any-return]
        view.variance,  # type: ignore[union-attr]
        view.sum_of_weights,  # type: ignore[union-attr]
        out=np.full(view.sum_of_weights.shape, np.nan),  # type: ignore[union-attr]
        where=view.sum_of_weights > 1,  # type: ignore[union-attr]
        where=view.sum_of_weights**2 > view.sum_of_weights_squared,
    )

Expected behavior

Not to strip a type ignore comment!!!

(Personally, I think all trailing comments should be ignored from all line length calculations, etc, since they are often turning off linting or type checking for the line they are on. But it clearly shouldn't just vanish!)

Environment

  • Black's version: main and 22.1.0
  • OS and Python version: Any (macOS, pre-commit.ci's linux, and whatever the web app runs on)

Additional context

Pretty self contained. :) I had noticed a similar error on upgrading to 22.1.0, but it went away due to other changes, and I never worked it back down, but I'm hoping it was the same one.

Metadata

Metadata

Assignees

Labels

C: invalid codeBlack destroyed a valid Python fileF: commentsThe syntactic kind. Not in the language grammar, always on our minds. Best bugs.T: bugSomething isn't working
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions