remove obviously unnecessary parentheses (#850)

Fixes #548
This commit is contained in:
Jelle Zijlstra 2019-05-15 21:11:04 -07:00 committed by GitHub
parent 188c31db7c
commit 957ba24bb6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 41 additions and 2 deletions

View File

@ -1602,6 +1602,26 @@ def visit_default(self, node: LN) -> Iterator[Line]:
self.current_line.append(node)
yield from super().visit_default(node)
def visit_atom(self, node: Node) -> Iterator[Line]:
# Always make parentheses invisible around a single node, because it should
# not be needed (except in the case of yield, where removing the parentheses
# produces a SyntaxError).
if (
len(node.children) == 3
and isinstance(node.children[0], Leaf)
and node.children[0].type == token.LPAR
and isinstance(node.children[2], Leaf)
and node.children[2].type == token.RPAR
and isinstance(node.children[1], Leaf)
and not (
node.children[1].type == token.NAME
and node.children[1].value == "yield"
)
):
node.children[0].value = ""
node.children[2].value = ""
yield from super().visit_default(node)
def visit_INDENT(self, node: Node) -> Iterator[Line]:
"""Increase indentation level, maybe yield a line."""
# In blib2to3 INDENT never holds comments.

View File

@ -158,7 +158,8 @@
+{"2.7": dead, "3.7": long_live or die_hard}
+{"2.7", "3.6", "3.7", "3.8", "3.9", "4.0" if gilectomy else "3.10"}
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10 or A, 11 or B, 12 or C]
(SomeName)
-(SomeName)
+SomeName
SomeName
(Good, Bad, Ugly)
(i for i in (1, 2, 3))

View File

@ -410,7 +410,7 @@ async def f():
{"2.7": dead, "3.7": long_live or die_hard}
{"2.7", "3.6", "3.7", "3.8", "3.9", "4.0" if gilectomy else "3.10"}
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10 or A, 11 or B, 12 or C]
(SomeName)
SomeName
SomeName
(Good, Bad, Ugly)
(i for i in (1, 2, 3))

View File

@ -0,0 +1,10 @@
print((1))
x = (1)
x = (1.2)
(x) = (3)
# output
print(1)
x = 1
x = 1.2
x = 3

View File

@ -436,6 +436,14 @@ def test_empty_lines(self) -> None:
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, black.FileMode())
@patch("black.dump_to_file", dump_to_stderr)
def test_remove_parens(self) -> None:
source, expected = read_data("remove_parens")
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_string_prefixes(self) -> None:
source, expected = read_data("string_prefixes")