diff --git a/CHANGES.md b/CHANGES.md index 35522381fab..76993ca3fe4 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -22,6 +22,7 @@ +- Fix `fix_fmt_skip_in_one_liners` crashing on `with` statements (#4853) - Fix `fix_fmt_skip_in_one_liners` crashing on annotated parameters (#4854) ### Configuration diff --git a/src/black/comments.py b/src/black/comments.py index 13c9926d03b..de1831e4d7c 100644 --- a/src/black/comments.py +++ b/src/black/comments.py @@ -650,10 +650,21 @@ def _generate_ignored_nodes_from_fmt_skip( current_node.prefix = "" break + # Special case for with expressions + # Without this, we can stuck inside the asexpr_test's children's children + if ( + current_node.parent + and current_node.parent.type == syms.asexpr_test + and current_node.parent.parent + and current_node.parent.parent.type == syms.with_stmt + ): + current_node = current_node.parent + ignored_nodes.insert(0, current_node) if current_node.prev_sibling is None and current_node.parent is not None: current_node = current_node.parent + # Special handling for compound statements with semicolon-separated bodies if Preview.fix_fmt_skip_in_one_liners in mode and isinstance(parent, Node): body_node = _find_compound_statement_context(parent) diff --git a/tests/data/cases/fmtskip12.py b/tests/data/cases/fmtskip12.py new file mode 100644 index 00000000000..3af6b4443a1 --- /dev/null +++ b/tests/data/cases/fmtskip12.py @@ -0,0 +1,21 @@ +# flags: --preview + +with open("file.txt") as f: content = f.read() # fmt: skip + +# Ideally, only the last line would be ignored +# But ignoring only part of the asexpr_test causes a parse error +# Same with ignoring the asexpr_test without also ignoring the entire with_stmt +with open ( + "file.txt" , +) as f: content = f.read() # fmt: skip + +# output + +with open("file.txt") as f: content = f.read() # fmt: skip + +# Ideally, only the last line would be ignored +# But ignoring only part of the asexpr_test causes a parse error +# Same with ignoring the asexpr_test without also ignoring the entire with_stmt +with open ( + "file.txt" , +) as f: content = f.read() # fmt: skip