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

Chris Angelico rosuav at gmail.com
Sun Mar 9 02:46:53 CET 2014


On Sun, Mar 9, 2014 at 11:44 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> 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))

Somewhat possible, but it's kinda too late at that point; you've
already gone via float. It's of some use, perhaps, but it doesn't
actually let you "do more". I was hoping to get the source string
before it got floated, and to make a decimal out of it instead. But by
that time, it's already actually become a float, and the AST node.n
is, as you demonstrate here, an actual float.

I tried substituting in a Decimal instead of building up a call to
Decimal("..."), but compile() won't touch it:

>>> ast.dump(node)
"Expression(body=BinOp(left=Num(n=Decimal('2.5')), op=Add(),
right=BinOp(left=Num(n=5), op=Pow(), right=Num(n=Decimal('0.5')))))"
>>> compile(node,"<...>","eval")
Traceback (most recent call last):
  File "<pyshell#15>", line 1, in <module>
    compile(node,"<...>","eval")
TypeError: non-numeric type in Num

Awwwww :(

ChrisA


More information about the Python-ideas mailing list