Fix crash on type comment with trailing space (#3773)

This commit is contained in:
Shantanu 2023-07-09 16:28:26 -07:00 committed by GitHub
parent 257d392217
commit b8e2ec728c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 13 additions and 3 deletions

View File

@ -19,6 +19,8 @@
under some circumstances. (#3745) under some circumstances. (#3745)
- Fix a bug where multi-line open parenthesis magic comment like `type: ignore` were not - Fix a bug where multi-line open parenthesis magic comment like `type: ignore` were not
correctly parsed (#3740) correctly parsed (#3740)
- Fix error in AST validation when Black removes trailing whitespace in a type comment
(#3773)
### Preview style ### Preview style

View File

@ -208,15 +208,18 @@ def stringify_ast(node: ast.AST, depth: int = 0) -> Iterator[str]:
else: else:
normalized: object 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 ( if (
isinstance(node, ast.Constant) isinstance(node, ast.Constant)
and field == "value" and field == "value"
and isinstance(value, str) 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) normalized = _normalize("\n", value)
elif field == "type_comment" and isinstance(value, str):
# Trailing whitespace in type comments is removed.
normalized = value.rstrip()
else: else:
normalized = value normalized = value
yield f"{' ' * (depth+2)}{normalized!r}, # {value.__class__.__name__}" yield f"{' ' * (depth+2)}{normalized!r}, # {value.__class__.__name__}"

View File

@ -154,6 +154,9 @@ def _init_host(self, parsed) -> None:
not parsed.hostname.strip()): not parsed.hostname.strip()):
pass pass
a = "type comment with trailing space" # type: str
####################### #######################
### SECTION COMMENT ### ### SECTION COMMENT ###
####################### #######################
@ -332,6 +335,8 @@ def _init_host(self, parsed) -> None:
pass pass
a = "type comment with trailing space" # type: str
####################### #######################
### SECTION COMMENT ### ### SECTION COMMENT ###
####################### #######################