Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import ast
import decimal
class ConstantTransformer(ast.NodeTransformer):
def visit_Constant(self, node):
decimal = ast.copy_location(ast.Name(id='decimal', ctx=ast.Load()), node)
Decimal = ast.copy_location(ast.Attribute(value=decimal, attr='Decimal', ctx=ast.Load()),node)
Constant = ast.copy_location(ast.Str(s=str(node.n)), node)
return ast.copy_location(ast.Call(func=Decimal,args=[Constant],keywords=[]),node)
expr = '0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1'
node = ast.parse(expr, '', 'eval')
ConstantTransformer().visit(node)
print(ast.dump(node))
print(eval((compile(node, '', 'eval'))))
@sigmadream

This comment has been minimized.

Copy link
Owner Author

@sigmadream sigmadream commented May 19, 2021

➜  python ConstantTransformer.py 
Expression(body=BinOp(left=BinOp(left=BinOp(left=BinOp(left=BinOp(left=BinOp(left=BinOp(left=BinOp(left=BinOp(left=Call(func=Attribute(value=Name(id='decimal', ctx=Load()), attr='Decimal', ctx=Load()), args=[Constant(value='0.1')], keywords=[]), op=Add(), right=Call(func=Attribute(value=Name(id='decimal', ctx=Load()), attr='Decimal', ctx=Load()), args=[Constant(value='0.1')], keywords=[])), op=Add(), right=Call(func=Attribute(value=Name(id='decimal', ctx=Load()), attr='Decimal', ctx=Load()), args=[Constant(value='0.1')], keywords=[])), op=Add(), right=Call(func=Attribute(value=Name(id='decimal', ctx=Load()), attr='Decimal', ctx=Load()), args=[Constant(value='0.1')], keywords=[])), op=Add(), right=Call(func=Attribute(value=Name(id='decimal', ctx=Load()), attr='Decimal', ctx=Load()), args=[Constant(value='0.1')], keywords=[])), op=Add(), right=Call(func=Attribute(value=Name(id='decimal', ctx=Load()), attr='Decimal', ctx=Load()), args=[Constant(value='0.1')], keywords=[])), op=Add(), right=Call(func=Attribute(value=Name(id='decimal', ctx=Load()), attr='Decimal', ctx=Load()), args=[Constant(value='0.1')], keywords=[])), op=Add(), right=Call(func=Attribute(value=Name(id='decimal', ctx=Load()), attr='Decimal', ctx=Load()), args=[Constant(value='0.1')], keywords=[])), op=Add(), right=Call(func=Attribute(value=Name(id='decimal', ctx=Load()), attr='Decimal', ctx=Load()), args=[Constant(value='0.1')], keywords=[])), op=Add(), right=Call(func=Attribute(value=Name(id='decimal', ctx=Load()), attr='Decimal', ctx=Load()), args=[Constant(value='0.1')], keywords=[])))
1.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment