Skip to content

Commit c81dbfb

Browse files
committed
Represent negative numbers as a USub UnaryOp so that the ast roundtrips
1 parent 523364b commit c81dbfb

File tree

2 files changed

+10
-1
lines changed

2 files changed

+10
-1
lines changed

src/python_minifier/__init__.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import re
99

1010
from python_minifier.ast_compare import CompareError, compare_ast
11+
from python_minifier.ast_printer import print_ast
1112
from python_minifier.module_printer import ModulePrinter
1213
from python_minifier.rename import (
1314
rename_literals,
@@ -154,7 +155,9 @@ def minify(
154155
module = RemoveExplicitReturnNone()(module)
155156

156157
if constant_folding:
158+
print(print_ast(module))
157159
module = FoldConstants()(module)
160+
print(print_ast(module))
158161

159162
bind_names(module)
160163
resolve_names(module)
@@ -220,6 +223,8 @@ def unparse(module):
220223
printer = ModulePrinter()
221224
printer(module)
222225

226+
print(printer.code)
227+
223228
try:
224229
minified_module = ast.parse(printer.code, 'python_minifier.unparse output')
225230
except SyntaxError as syntax_error:

src/python_minifier/transforms/constant_folding.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,11 @@ def visit_BinOp(self, node):
3939
elif isinstance(value, bool):
4040
new_node = ast.NameConstant(value=value)
4141
elif isinstance(value, (int, float, complex)):
42-
new_node = ast.Num(n=value)
42+
if value < 0:
43+
# Represent negative numbers as a USub UnaryOp, so that the ast roundtrip is correct
44+
new_node = ast.UnaryOp(op=ast.USub(), operand=ast.Num(n=-value))
45+
else:
46+
new_node = ast.Num(n=value)
4347
else:
4448
return node
4549

0 commit comments

Comments
 (0)