From f5a6b3e860c848a94ad635adf4afdefdbf031118 Mon Sep 17 00:00:00 2001 From: David Szotten Date: Wed, 12 Aug 2020 17:11:11 +0100 Subject: [PATCH] don't strip brackets before lsqb (#1575) it's not safe to remove brackets that are followed by a `[` --- src/black/__init__.py | 7 +++++-- tests/data/bracketed_slicing.py | 3 +++ tests/test_black.py | 8 ++++++++ 3 files changed, 16 insertions(+), 2 deletions(-) create mode 100644 tests/data/bracketed_slicing.py diff --git a/src/black/__init__.py b/src/black/__init__.py index 930f2cb0ae5..430bbcb4c94 100644 --- a/src/black/__init__.py +++ b/src/black/__init__.py @@ -3287,8 +3287,11 @@ def do_match(self, line: Line) -> TMatchResult: and LL[next_idx].type == token.RPAR and not is_empty_rpar(LL[next_idx]) ): - # That RPAR should NOT be followed by a '.' symbol. - if is_valid_index(next_idx + 1) and LL[next_idx + 1].type == token.DOT: + # That RPAR should NOT be followed by a '.' or a '[' + if is_valid_index(next_idx + 1) and LL[next_idx + 1].type in { + token.DOT, + token.LSQB, + }: continue return Ok(string_idx) diff --git a/tests/data/bracketed_slicing.py b/tests/data/bracketed_slicing.py new file mode 100644 index 00000000000..17543fa2676 --- /dev/null +++ b/tests/data/bracketed_slicing.py @@ -0,0 +1,3 @@ +("" % a)[0] +# output +("" % a)[0] diff --git a/tests/test_black.py b/tests/test_black.py index 3ed5daa4b49..2ded6f8a7e7 100644 --- a/tests/test_black.py +++ b/tests/test_black.py @@ -487,6 +487,14 @@ def test_slices(self) -> None: black.assert_equivalent(source, actual) black.assert_stable(source, actual, black.FileMode()) + @patch("black.dump_to_file", dump_to_stderr) + def test_bracketed_slicing(self) -> None: + source, expected = read_data("bracketed_slicing") + actual = fs(source) + self.assertFormatEqual(expected, actual) + black.assert_equivalent(source, actual) + black.assert_stable(source, actual, black.FileMode()) + @patch("black.dump_to_file", dump_to_stderr) def test_comments(self) -> None: source, expected = read_data("comments")