Skip to content

Commit

Permalink
bpo-38870: Do not separate factor prefixes in ast.unparse (GH-20133)
Browse files Browse the repository at this point in the history
  • Loading branch information
isidentical committed May 16, 2020
1 parent d5b3f6b commit ce4a753
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
9 changes: 6 additions & 3 deletions Lib/ast.py
Expand Up @@ -1190,18 +1190,21 @@ def visit_Tuple(self, node):

unop = {"Invert": "~", "Not": "not", "UAdd": "+", "USub": "-"}
unop_precedence = {
"~": _Precedence.FACTOR,
"not": _Precedence.NOT,
"~": _Precedence.FACTOR,
"+": _Precedence.FACTOR,
"-": _Precedence.FACTOR
"-": _Precedence.FACTOR,
}

def visit_UnaryOp(self, node):
operator = self.unop[node.op.__class__.__name__]
operator_precedence = self.unop_precedence[operator]
with self.require_parens(operator_precedence, node):
self.write(operator)
self.write(" ")
# factor prefixes (+, -, ~) shouldn't be seperated
# from the value they belong, (e.g: +1 instead of + 1)
if operator_precedence is not _Precedence.FACTOR:
self.write(" ")
self.set_precedence(operator_precedence, node.operand)
self.traverse(node.operand)

Expand Down
8 changes: 7 additions & 1 deletion Lib/test/test_unparse.py
Expand Up @@ -347,7 +347,7 @@ def test_simple_expressions_parens(self):
self.check_src_roundtrip("(1 + 2) / 3")
self.check_src_roundtrip("(1 + 2) * 3 + 4 * (5 + 2)")
self.check_src_roundtrip("(1 + 2) * 3 + 4 * (5 + 2) ** 2")
self.check_src_roundtrip("~ x")
self.check_src_roundtrip("~x")
self.check_src_roundtrip("x and y")
self.check_src_roundtrip("x and y and z")
self.check_src_roundtrip("x and (y and x)")
Expand Down Expand Up @@ -401,6 +401,12 @@ def test_docstrings_negative_cases(self):
self.check_ast_roundtrip(src)
self.check_src_dont_roundtrip(src)

def test_unary_op_factor(self):
for prefix in ("+", "-", "~"):
self.check_src_roundtrip(f"{prefix}1")
for prefix in ("not",):
self.check_src_roundtrip(f"{prefix} 1")

class DirectoryTestCase(ASTTestCase):
"""Test roundtrip behaviour on all files in Lib and Lib/test."""

Expand Down

0 comments on commit ce4a753

Please sign in to comment.