[Python-ideas] Python Numbers as Human Concept Decimal System

Steven D'Aprano steve at pearwood.info
Sun Mar 9 01:44:36 CET 2014


On Sun, Mar 09, 2014 at 11:07:21AM +1100, Chris Angelico wrote:
> On Sun, Mar 9, 2014 at 10:48 AM, Terry Reedy <tjreedy at udel.edu> wrote:
> > It might be possible to experiment with this in Idle. It already does some
> > parsing of user input as typed in order to color code it, though that may
> > not recognize float literals. If not, let float_lit = <re that recognizes
> > float literals>. Then use re.sub to replace 'xx.yy', etc, with 'D("xx.yy")'
> > before sending user input to the subprocess. When auto-decimal mode is set,
> > display and send 'from decimal import Decimal as D' to the user-process and
> > change the prompt to, for instance
> 
> I played with the possibility of an AST transform, but by the time
> it's compiled into an AST, it's too late - the string has already been
> floated. A regex would be a fairly hefty hammer, I think.

Great minds think alike :-)

An AST transformation is possible:


import ast

class MyTransformer(ast.NodeTransformer):
    def visit_Num(self, node):
        # Transform float literals to Decimal("literal").
        if isinstance(node.n, float):
            quoted_literal = ast.Str(repr(node.n))
            new_node =ast.Call(
                    func=ast.Name(id='Decimal', ctx=ast.Load()),
                    args=[quoted_literal],
                    )
            return ast.copy_location(new_node, node)
        return node

node = ast.parse('2.5 + 5**0.5', mode='eval')
print("Before:")
ast.dump(node)
print("After:")
ast.dump(MyTransformer().generic_visit(node))



I tried to find some way to hook that transformation into the code 
module, so as to give an intereactive interpreter with decimal floats, 
but couldn't work out how to do so.


-- 
Steven


More information about the Python-ideas mailing list