Skip to content

Commit b8e2ec7

Browse files
authored
Fix crash on type comment with trailing space (#3773)
1 parent 257d392 commit b8e2ec7

File tree

3 files changed

+13
-3
lines changed

3 files changed

+13
-3
lines changed

CHANGES.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@
1919
under some circumstances. (#3745)
2020
- Fix a bug where multi-line open parenthesis magic comment like `type: ignore` were not
2121
correctly parsed (#3740)
22+
- Fix error in AST validation when Black removes trailing whitespace in a type comment
23+
(#3773)
2224

2325
### Preview style
2426

src/black/parsing.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -208,15 +208,18 @@ def stringify_ast(node: ast.AST, depth: int = 0) -> Iterator[str]:
208208

209209
else:
210210
normalized: object
211-
# Constant strings may be indented across newlines, if they are
212-
# docstrings; fold spaces after newlines when comparing. Similarly,
213-
# trailing and leading space may be removed.
214211
if (
215212
isinstance(node, ast.Constant)
216213
and field == "value"
217214
and isinstance(value, str)
218215
):
216+
# Constant strings may be indented across newlines, if they are
217+
# docstrings; fold spaces after newlines when comparing. Similarly,
218+
# trailing and leading space may be removed.
219219
normalized = _normalize("\n", value)
220+
elif field == "type_comment" and isinstance(value, str):
221+
# Trailing whitespace in type comments is removed.
222+
normalized = value.rstrip()
220223
else:
221224
normalized = value
222225
yield f"{' ' * (depth+2)}{normalized!r}, # {value.__class__.__name__}"

tests/data/simple_cases/comments2.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,9 @@ def _init_host(self, parsed) -> None:
154154
not parsed.hostname.strip()):
155155
pass
156156

157+
158+
a = "type comment with trailing space" # type: str
159+
157160
#######################
158161
### SECTION COMMENT ###
159162
#######################
@@ -332,6 +335,8 @@ def _init_host(self, parsed) -> None:
332335
pass
333336

334337

338+
a = "type comment with trailing space" # type: str
339+
335340
#######################
336341
### SECTION COMMENT ###
337342
#######################

0 commit comments

Comments
 (0)