Add parentheses around numeric literals, to avoid turning 3 .bit_length() into 3.bit_length().

This commit is contained in:
Mark Dickinson 2010-06-29 08:52:36 +00:00
parent 82c8d93357
commit 3eb0290346
2 changed files with 14 additions and 10 deletions

View file

@ -84,6 +84,9 @@ class UnparseTestCase(unittest.TestCase):
self.check_roundtrip("not True or False") self.check_roundtrip("not True or False")
self.check_roundtrip("True or not False") self.check_roundtrip("True or not False")
def test_integer_parens(self):
self.check_roundtrip("3 .__abs__()")
def test_chained_comparisons(self): def test_chained_comparisons(self):
self.check_roundtrip("1 < 4 <= 5") self.check_roundtrip("1 < 4 <= 5")
self.check_roundtrip("a is b is c is not d") self.check_roundtrip("a is b is c is not d")

View file

@ -302,16 +302,17 @@ class Unparser:
self.write("`") self.write("`")
def _Num(self, t): def _Num(self, t):
# There are no negative numeric literals in Python; however, # Add parentheses around numeric literals to avoid:
# some optimizations produce a negative Num in the AST. Add #
# parentheses to avoid turning (-1)**2 into -1**2. # (1) turning (-1)**2 into -1**2, and
strnum = repr(t.n) # (2) turning 3 .__abs__() into 3.__abs__()
if strnum.startswith("-"): #
self.write("(") # For (1), note that Python doesn't actually have negative
self.write(strnum) # numeric literals, but (at least in Python 2.x) there's a CST
self.write(")") # transformation that can produce negative Nums in the AST.
else: self.write("(")
self.write(strnum) self.write(repr(t.n))
self.write(")")
def _List(self, t): def _List(self, t):
self.write("[") self.write("[")