Skip to content

Commit

Permalink
Standardize type comments to always have one space (#2698)
Browse files Browse the repository at this point in the history
  • Loading branch information
Pedro-Muller29 committed Sep 27, 2024
1 parent 68cd137 commit 51c5134
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 11 deletions.
1 change: 1 addition & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
17 changes: 12 additions & 5 deletions src/black/comments.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
55 changes: 49 additions & 6 deletions tests/data/cases/type_comment_syntax_error.py
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 51c5134

Please sign in to comment.