diff --git a/CHANGES.md b/CHANGES.md index 97e8645e3ea..b73a9eb7ad1 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -22,6 +22,7 @@ - Fix crashes involving comments in parenthesised return types or `X | Y` style unions. (#4453) - Fix skipping Jupyter cells with unknown `%%` magic (#4462) +- Standardize type comments to always have one space (#4467) ### Preview style diff --git a/src/black/comments.py b/src/black/comments.py index cd37c440290..fce25c1c1ce 100644 --- a/src/black/comments.py +++ b/src/black/comments.py @@ -153,13 +153,20 @@ def make_comment(content: str) -> str: if content[0] == "#": content = content[1:] + NON_BREAKING_SPACE = " " - if ( - content - and content[0] == NON_BREAKING_SPACE - and not content.lstrip().startswith("type:") - ): + + is_type_comment = re.match(r"^\s*type:", content) + is_not_type_ignore = re.match(r"^\s*type:(?!\s*ignore\b)", content) + + if content and content[0] == NON_BREAKING_SPACE and not is_type_comment: content = " " + content[1:] # Replace NBSP by a simple space + elif is_type_comment and is_not_type_ignore and NON_BREAKING_SPACE not in content: + content = content.strip() + parts = content.split(":") + key = parts[0].strip() # Remove extra spaces around "type" + value = parts[1].strip() # Remove extra spaces around the value part + content = f" {key}: {value}" if content and content[0] not in COMMENT_EXCEPTIONS: content = " " + content return "#" + content diff --git a/tests/data/cases/type_comment_syntax_error.py b/tests/data/cases/type_comment_syntax_error.py index 2e5ca2ede8c..4c491258df3 100644 --- a/tests/data/cases/type_comment_syntax_error.py +++ b/tests/data/cases/type_comment_syntax_error.py @@ -1,11 +1,54 @@ -def foo( - # type: Foo - x): pass +def f( + a, # type: int +): + pass + + +# test type comments +def f(a, b, c, d, e, f, g, h, i): + # type: (int, int, int, int, int, int, int, int, int) -> None + pass + + +def f( + a, # type : int + b, # type : int + c, #type : int + d, # type: int + e, # type: int + f, # type : int + g, #type:int + h, # type: int + i, # type: int +): + # type: (...) -> None + pass + + # output +def f( + a, # type: int +): + pass + + +# test type comments +def f(a, b, c, d, e, f, g, h, i): + # type: (int, int, int, int, int, int, int, int, int) -> None + pass + -def foo( - # type: Foo - x, +def f( + a, # type : int + b, # type : int + c, # type : int + d, # type: int + e, # type: int + f, # type : int + g, # type: int + h, # type: int + i, # type: int ): + # type: (...) -> None pass