Skip to content

Commit

Permalink
don't strip brackets before e.g. lsqb (psf#1575)
Browse files Browse the repository at this point in the history
it's not safe to remove brackets that are followed by an operator with
lower precedence than PERCENT
  • Loading branch information
davidszotten committed Aug 13, 2020
1 parent b59a524 commit 5b5e65f
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 3 deletions.
13 changes: 10 additions & 3 deletions src/black/__init__.py
Expand Up @@ -3238,7 +3238,8 @@ class StringParenStripper(StringTransformer):
Requirements:
The line contains a string which is surrounded by parentheses and:
- The target string is NOT the only argument to a function call).
- The RPAR is NOT followed by an attribute access (i.e. a dot).
- The RPAR is NOT followed by an operator with higher precedence
than PERCENT.
Transformations:
The parentheses mentioned in the 'Requirements' section are stripped.
Expand Down Expand Up @@ -3287,8 +3288,14 @@ 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 anything with higher
# precedence than PERCENT
if is_valid_index(next_idx + 1) and LL[next_idx + 1].type in {
token.DOUBLESTAR,
token.LSQB,
token.LPAR,
token.DOT,
}:
continue

return Ok(string_idx)
Expand Down
3 changes: 3 additions & 0 deletions tests/data/bracketed_slicing.py
@@ -0,0 +1,3 @@
("" % a)[0]
# output
("" % a)[0]
8 changes: 8 additions & 0 deletions tests/test_black.py
Expand Up @@ -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")
Expand Down

0 comments on commit 5b5e65f

Please sign in to comment.