Skip to content

Commit 5cfc118

Browse files
committed
Improve AST safety check
Fixes #4270, regressed by #4270
1 parent bf11956 commit 5cfc118

File tree

3 files changed

+19
-4
lines changed

3 files changed

+19
-4
lines changed

Diff for: CHANGES.md

+1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
### Stable style
1010

1111
<!-- Changes that affect Black's stable style -->
12+
- Fix unwanted crashes caused by AST equivalency check (#4290)
1213

1314
### Preview style
1415

Diff for: src/black/parsing.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -223,11 +223,9 @@ def _stringify_ast(node: ast.AST, parent_stack: List[ast.AST]) -> Iterator[str]:
223223
and field == "value"
224224
and isinstance(value, str)
225225
and len(parent_stack) >= 2
226+
# Any standalone string, ideally this would
227+
# exactly match black.nodes.is_docstring
226228
and isinstance(parent_stack[-1], ast.Expr)
227-
and isinstance(
228-
parent_stack[-2],
229-
(ast.FunctionDef, ast.AsyncFunctionDef, ast.Module, ast.ClassDef),
230-
)
231229
):
232230
# Constant strings may be indented across newlines, if they are
233231
# docstrings; fold spaces after newlines when comparing. Similarly,

Diff for: tests/test_black.py

+16
Original file line numberDiff line numberDiff line change
@@ -2908,6 +2908,22 @@ async def f():
29082908
"""docstring"""
29092909
''',
29102910
)
2911+
self.check_ast_equivalence(
2912+
"""
2913+
if __name__ == "__main__":
2914+
" docstring-like "
2915+
""",
2916+
'''
2917+
if __name__ == "__main__":
2918+
"""docstring-like"""
2919+
''',
2920+
)
2921+
self.check_ast_equivalence(r'def f(): r" \n "', r'def f(): "\\n"')
2922+
self.check_ast_equivalence('try: pass\nexcept: " x "', 'try: pass\nexcept: "x"')
2923+
2924+
self.check_ast_equivalence(
2925+
'def foo(): return " x "', 'def foo(): return "x"', should_fail=True
2926+
)
29112927

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

0 commit comments

Comments
 (0)