Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 8042e28

Browse files
committed
More unparse.py fixes:
- parenthesize lambdas, to avoid turning (lambda : int)() into lambda: int() - unparse an infinite float literals in the AST as an overflowing finite value unparse.py now successfully round-trips on all valid Lib/*.py and Lib/test/*.py files.
1 parent 3eb0290 commit 8042e28

2 files changed

Lines changed: 26 additions & 11 deletions

File tree

Demo/parser/test_unparse.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,13 @@ def test_unary_parens(self):
8787
def test_integer_parens(self):
8888
self.check_roundtrip("3 .__abs__()")
8989

90+
def test_huge_float(self):
91+
self.check_roundtrip("1e1000")
92+
self.check_roundtrip("-1e1000")
93+
94+
def test_lambda_parentheses(self):
95+
self.check_roundtrip("(lambda: int)()")
96+
9097
def test_chained_comparisons(self):
9198
self.check_roundtrip("1 < 4 <= 5")
9299
self.check_roundtrip("a is b is c is not d")

Demo/parser/unparse.py

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"Usage: unparse.py <path to source file>"
22
import sys
3+
import math
34
import ast
45
import tokenize
56
import io
@@ -302,17 +303,22 @@ def _Repr(self, t):
302303
self.write("`")
303304

304305
def _Num(self, t):
305-
# Add parentheses around numeric literals to avoid:
306-
#
307-
# (1) turning (-1)**2 into -1**2, and
308-
# (2) turning 3 .__abs__() into 3.__abs__()
309-
#
310-
# For (1), note that Python doesn't actually have negative
311-
# numeric literals, but (at least in Python 2.x) there's a CST
312-
# transformation that can produce negative Nums in the AST.
313-
self.write("(")
314-
self.write(repr(t.n))
315-
self.write(")")
306+
if isinstance(t.n, float):
307+
# A float literal should be nonnegative, and not a nan.
308+
# It could be an infinity, though; in that case we
309+
# substitute an overflowing decimal value.
310+
assert not math.isnan(t.n)
311+
assert math.copysign(1.0, t.n) > 0.0
312+
if math.isinf(t.n):
313+
self.write("1e" + repr(sys.float_info.max_10_exp + 1))
314+
else:
315+
self.write(repr(t.n))
316+
else:
317+
# Parenthesize integer literals to avoid turning
318+
# "3 .__abs__()" into "3.__abs__()".
319+
self.write("(")
320+
self.write(repr(t.n))
321+
self.write(")")
316322

317323
def _List(self, t):
318324
self.write("[")
@@ -539,10 +545,12 @@ def _keyword(self, t):
539545
self.dispatch(t.value)
540546

541547
def _Lambda(self, t):
548+
self.write("(")
542549
self.write("lambda ")
543550
self.dispatch(t.args)
544551
self.write(": ")
545552
self.dispatch(t.body)
553+
self.write(")")
546554

547555
def _alias(self, t):
548556
self.write(t.name)

0 commit comments

Comments
 (0)