black: is_type_comment() is wrong

Currently, the implementation of is_type_comment() looks like this:

def is_type_comment(leaf: Leaf, suffix: str = "") -> bool:
    """Return True if the given leaf is a special comment.
    Only returns true for type comments for now."""
    t = leaf.type
    v = leaf.value
    return t in {token.COMMENT, STANDALONE_COMMENT} and v.startswith("# type:" + suffix)

But this is wrong, because typed-ast also recognizes a comment with multiple spaces after the # as a type comment. Concretely this could lead Black to skip some of the checks we have to avoid moving type comments to the wrong line.

Ideally, Black should also standardize the formatting of type comments by cleaning up excessive whitespace after the # and after the :.

About this issue

  • Original URL
  • State: open
  • Created 6 years ago
  • Reactions: 1
  • Comments: 15 (5 by maintainers)

Commits related to this issue

Most upvoted comments

Should we also standardise spaces before the colon? Meaning we would accept (and fix) e.g. # type : Type or even # \t type : (some unexpected whitespace type) Type?

I think we shouldn’t normalize whitespace between “type” and the colon. Mypy also doesn’t recognize # type : int as a type comment.

Hey @IshanKamboj, sorry I’m not a black maintainer. I think you can start implementing right away and open a PR though 😃