Skip to content

Commit 836acad

Browse files
authored
Improve AST safety check (#4290)
Fixes #4288, regressed by #4270
1 parent 13bd092 commit 836acad

File tree

3 files changed

+20
-4
lines changed

3 files changed

+20
-4
lines changed

CHANGES.md

+2
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010

1111
<!-- Changes that affect Black's stable style -->
1212

13+
- Fix unwanted crashes caused by AST equivalency check (#4290)
14+
1315
### Preview style
1416

1517
<!-- Changes that affect Black's preview style -->

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,

tests/test_black.py

+16
Original file line numberDiff line numberDiff line change
@@ -2904,6 +2904,22 @@ async def f():
29042904
"""docstring"""
29052905
''',
29062906
)
2907+
self.check_ast_equivalence(
2908+
"""
2909+
if __name__ == "__main__":
2910+
" docstring-like "
2911+
""",
2912+
'''
2913+
if __name__ == "__main__":
2914+
"""docstring-like"""
2915+
''',
2916+
)
2917+
self.check_ast_equivalence(r'def f(): r" \n "', r'def f(): "\\n"')
2918+
self.check_ast_equivalence('try: pass\nexcept: " x "', 'try: pass\nexcept: "x"')
2919+
2920+
self.check_ast_equivalence(
2921+
'def foo(): return " x "', 'def foo(): return "x"', should_fail=True
2922+
)
29072923

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

0 commit comments

Comments
 (0)