-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwrap_integers.py
35 lines (29 loc) · 935 Bytes
/
wrap_integers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#!/usr/bin/python3
import ast
from fractions import Fraction
class IntegerWrapper(ast.NodeTransformer):
"""Wraps all integers in a call to Integer()"""
def visit_Num(self, node):
if isinstance(node.n, int):
return ast.Call(func=ast.Name(id='Integer', ctx=ast.Load()),
args=[node], keywords=[])
return node
class Integer(object):
def __init__(self, value):
self.value = value
def __truediv__(self, other):
if isinstance(other, Integer):
return Fraction(numerator=self.value, denominator=other.value)
code = "print((1/10)+(2/10))"
print(code)
print()
print("Without AST transformation:")
exec(code)
print()
print("With AST transformation:")
tree = ast.parse(code)
tree = IntegerWrapper().visit(tree)
# Add lineno & col_offset to the nodes we created
ast.fix_missing_locations(tree)
co = compile(tree, "<ast>", "exec")
exec(co)