bpo-38870: Do not separate factor prefixes in ast.unparse (GH-20133)

This commit is contained in:
Batuhan Taskaya 2020-05-17 00:46:11 +03:00 committed by GitHub
parent d5b3f6b7f9
commit ce4a753dcb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 13 additions and 4 deletions

View File

@ -1190,10 +1190,10 @@ class _Unparser(NodeVisitor):
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):
@ -1201,6 +1201,9 @@ class _Unparser(NodeVisitor):
operator_precedence = self.unop_precedence[operator]
with self.require_parens(operator_precedence, node):
self.write(operator)
# 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)

View File

@ -401,6 +401,12 @@ class CosmeticTestCase(ASTTestCase):
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."""