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
- #2097 issue: is_type_comment() update — committed to Aashka1/black by Aashka1 3 years ago
- is_type_comment now checks for extra or zero spaces (#2097) — committed to Pedro-Muller29/black by Pedro-Muller29 2 years ago
- is_type_comment now checks for extra or zero spaces (#2097) — committed to Pedro-Muller29/black by Pedro-Muller29 2 years ago
- is_type_comment now checks for extra or zero spaces (#2097) — committed to Pedro-Muller29/black by Pedro-Muller29 2 years ago
- Fix is_type_comment function issue #2097 — committed to WSU-CptS-581-2025/black_code_formatter by triet301 2 years ago
- Standardize type comments to form `# type: (value)` (psf#2097) Co-authored-by: Pedro Mezacasa Muller <Pedro-Muller29@users.noreply.github.com> — committed to ranjodhsingh1729/black by ranjodhsingh1729 2 years ago
- Fix #2097: Recognize type comments with spaces after # Updated comment recognition functions (is_type_comment, is_type_ignore_comment, and helpers) to correctly identify type/ignore comments even whe... — committed to anthonychen000/black by anthonychen000 2 years ago
Should we also standardise spaces before the colon? Meaning we would accept (and fix) e.g.
# type : Typeor 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 : intas 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 😃