Skip to content

Commit

Permalink
Improve AST safety check
Browse files Browse the repository at this point in the history
Fixes psf#4270, regressed by psf#4270
  • Loading branch information
hauntsaninja committed Mar 22, 2024
1 parent bf11956 commit c89a143
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
5 changes: 1 addition & 4 deletions src/black/parsing.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,11 +223,8 @@ def _stringify_ast(node: ast.AST, parent_stack: List[ast.AST]) -> Iterator[str]:
and field == "value"
and isinstance(value, str)
and len(parent_stack) >= 2
# Any standalone string, ideally this would exactly match black.nodes.is_docstring
and isinstance(parent_stack[-1], ast.Expr)
and isinstance(
parent_stack[-2],
(ast.FunctionDef, ast.AsyncFunctionDef, ast.Module, ast.ClassDef),
)
):
# Constant strings may be indented across newlines, if they are
# docstrings; fold spaces after newlines when comparing. Similarly,
Expand Down
16 changes: 16 additions & 0 deletions tests/test_black.py
Original file line number Diff line number Diff line change
Expand Up @@ -2908,6 +2908,22 @@ async def f():
"""docstring"""
''',
)
self.check_ast_equivalence(
"""
if __name__ == "__main__":
" docstring-like "
""",
'''
if __name__ == "__main__":
"""docstring-like"""
''',
)
self.check_ast_equivalence(r'def f(): r" \n "', r'def f(): "\\n"')
self.check_ast_equivalence('try: pass\nexcept: " x "', 'try: pass\nexcept: "x"')

self.check_ast_equivalence(
'def foo(): return " x "', 'def foo(): return "x"', should_fail=True
)

def test_assert_equivalent_fstring(self) -> None:
major, minor = sys.version_info[:2]
Expand Down

0 comments on commit c89a143

Please sign in to comment.