Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix crash on type comment with trailing space #3773

Merged
merged 3 commits into from
Jul 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
PEP 604 unions (#3735)
- 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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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