Skip to content

Commit

Permalink
Fix crash on type comment with trailing space (#3773)
Browse files Browse the repository at this point in the history
  • Loading branch information
hauntsaninja committed Jul 9, 2023
1 parent 257d392 commit b8e2ec7
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 3 deletions.
2 changes: 2 additions & 0 deletions CHANGES.md
Expand Up @@ -19,6 +19,8 @@
under some circumstances. (#3745)
- Fix a bug where multi-line open parenthesis magic comment like `type: ignore` were not
correctly parsed (#3740)
- Fix error in AST validation when Black removes trailing whitespace in a type comment
(#3773)

### Preview style

Expand Down
9 changes: 6 additions & 3 deletions src/black/parsing.py
Expand Up @@ -208,15 +208,18 @@ def stringify_ast(node: ast.AST, depth: int = 0) -> Iterator[str]:

else:
normalized: object
# Constant strings may be indented across newlines, if they are
# docstrings; fold spaces after newlines when comparing. Similarly,
# trailing and leading space may be removed.
if (
isinstance(node, ast.Constant)
and field == "value"
and isinstance(value, str)
):
# Constant strings may be indented across newlines, if they are
# docstrings; fold spaces after newlines when comparing. Similarly,
# trailing and leading space may be removed.
normalized = _normalize("\n", value)
elif field == "type_comment" and isinstance(value, str):
# Trailing whitespace in type comments is removed.
normalized = value.rstrip()
else:
normalized = value
yield f"{' ' * (depth+2)}{normalized!r}, # {value.__class__.__name__}"
Expand Down
5 changes: 5 additions & 0 deletions tests/data/simple_cases/comments2.py
Expand Up @@ -154,6 +154,9 @@ def _init_host(self, parsed) -> None:
not parsed.hostname.strip()):
pass


a = "type comment with trailing space" # type: str

#######################
### SECTION COMMENT ###
#######################
Expand Down Expand Up @@ -332,6 +335,8 @@ def _init_host(self, parsed) -> None:
pass


a = "type comment with trailing space" # type: str

#######################
### SECTION COMMENT ###
#######################
Expand Down

0 comments on commit b8e2ec7

Please sign in to comment.