berkerpeksag / astor

Python AST read/write
https://pypi.org/project/astor/
BSD 3-Clause "New" or "Revised" License
803 stars 102 forks source link

Added dumping large numbers in hex #152

Closed KOLANICH closed 4 years ago

KOLANICH commented 5 years ago
From 37d32422a5bb3041cce81a955dfe5393124552af Mon Sep 17 00:00:00 2001
From: KOLANICH <KOLANICH@users.noreply.github.com>
Date: Sun, 21 Jul 2019 19:41:19 +0000
Subject: [PATCH] Added dumping large numbers in hex

---
 astor/code_gen.py | 8 ++++++++
 1 file changed, 8 insertions(+)

diff --git a/astor/code_gen.py b/astor/code_gen.py
index 0d8bd6b..82a6a50 100644
--- a/astor/code_gen.py
+++ b/astor/code_gen.py
@@ -653,8 +653,16 @@ def visit_Str(self, node):
     def visit_Bytes(self, node):
         self.write(repr(node.s))

+    HEX_THRESHOLD = 10**17 # since that hex is more succinct
     def _handle_numeric_constant(self, value):
         x = value
+        if isinstance(x, int):
+            if abs(x) >= __class__.HEX_THRESHOLD:
+                s = hex(x)
+            else:
+                s = repr(x)
+            self.write(s)
+            return

         def part(p, imaginary):
             # Represent infinity as 1e1000 and NaN as 1e1000-1e1000.
berkerpeksag commented 4 years ago

Thanks, but I don't think the gain is big enough to worth changing the implementation. Also, now that we've fixed usage of a custom generator class, this behavior could easily be implemented by overriding visit_Num or visit_Constant methods.