Skip to content

Commit 51c5134

Browse files
Standardize type comments to always have one space (#2698)
1 parent 68cd137 commit 51c5134

File tree

3 files changed

+62
-11
lines changed

3 files changed

+62
-11
lines changed

CHANGES.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
- Fix crashes involving comments in parenthesised return types or `X | Y` style unions.
2323
(#4453)
2424
- Fix skipping Jupyter cells with unknown `%%` magic (#4462)
25+
- Standardize type comments to always have one space (#4467)
2526

2627
### Preview style
2728

src/black/comments.py

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -153,13 +153,20 @@ def make_comment(content: str) -> str:
153153

154154
if content[0] == "#":
155155
content = content[1:]
156+
156157
NON_BREAKING_SPACE = " "
157-
if (
158-
content
159-
and content[0] == NON_BREAKING_SPACE
160-
and not content.lstrip().startswith("type:")
161-
):
158+
159+
is_type_comment = re.match(r"^\s*type:", content)
160+
is_not_type_ignore = re.match(r"^\s*type:(?!\s*ignore\b)", content)
161+
162+
if content and content[0] == NON_BREAKING_SPACE and not is_type_comment:
162163
content = " " + content[1:] # Replace NBSP by a simple space
164+
elif is_type_comment and is_not_type_ignore and NON_BREAKING_SPACE not in content:
165+
content = content.strip()
166+
parts = content.split(":")
167+
key = parts[0].strip() # Remove extra spaces around "type"
168+
value = parts[1].strip() # Remove extra spaces around the value part
169+
content = f" {key}: {value}"
163170
if content and content[0] not in COMMENT_EXCEPTIONS:
164171
content = " " + content
165172
return "#" + content
Lines changed: 49 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,54 @@
1-
def foo(
2-
# type: Foo
3-
x): pass
1+
def f(
2+
a, # type: int
3+
):
4+
pass
5+
6+
7+
# test type comments
8+
def f(a, b, c, d, e, f, g, h, i):
9+
# type: (int, int, int, int, int, int, int, int, int) -> None
10+
pass
11+
12+
13+
def f(
14+
a, # type : int
15+
b, # type : int
16+
c, #type : int
17+
d, # type: int
18+
e, # type: int
19+
f, # type : int
20+
g, #type:int
21+
h, # type: int
22+
i, # type: int
23+
):
24+
# type: (...) -> None
25+
pass
26+
27+
428

529
# output
30+
def f(
31+
a, # type: int
32+
):
33+
pass
34+
35+
36+
# test type comments
37+
def f(a, b, c, d, e, f, g, h, i):
38+
# type: (int, int, int, int, int, int, int, int, int) -> None
39+
pass
40+
641

7-
def foo(
8-
# type: Foo
9-
x,
42+
def f(
43+
a, # type : int
44+
b, # type : int
45+
c, # type : int
46+
d, # type: int
47+
e, # type: int
48+
f, # type : int
49+
g, # type: int
50+
h, # type: int
51+
i, # type: int
1052
):
53+
# type: (...) -> None
1154
pass

0 commit comments

Comments
 (0)