[Python-ideas] Retain string form of AST Numbers

Terry Reedy tjreedy at udel.edu
Sat Apr 5 22:31:44 CEST 2014


On 4/5/2014 10:03 AM, Chris Angelico wrote:
> On Sun, Apr 6, 2014 at 12:32 AM, Ryan <rymg19 at gmail.com> wrote:
>> I could probably try that if you give a slightly clearer description.
>
> Currently, you can fire up IDLE or interactive Python and use it as a
> super calculator:
>
>>>> 1 + 2
> 3
>
> And when you use it with non-integers, you get floats:
>
>>>> 0.1 + 0.2
> 0.30000000000000004
>
> We could turn this into a Decimal calculator with two important changes:
> 1) Every instance of a number in the code must become a Decimal (which
> really means wrapping every number with Decimal("...") and importing
> Decimal from decimal)
> 2) Monkey-patch Decimal.__repr__ = Decimal.__str__ to make the display tidy
>
> The latter might be better done by subclassing Decimal and putting
> something into the builtins, but that's implementation detail (now
> that Decimal is implemented in C, its attributes can't be set).
>
> If that can be done without any core language changes, that would be awesome.

One could certainly do something with Idle without changing Python. Idle 
has an extension mechanism that operates by modifying runtime 
structures. I believe it is mainly used to add menu entries for 
functions that operate on the edit buffer wrapped by an editor window. 
Thus it should be possible to 'decimalize' a file by adding an import 
(or subclass definition) at the top of the buffer and wrap literals with 
D("...").

I don't think that the existing hooks are enough to modify the behavior 
of the Shell. For that, one could write python code to permanently patch 
the Shell to add a decimal mode. It would need to send initialization 
code to each user subprocess and wrap literals as above, either as typed 
or before sending.

When I have more time than I do now, I would be willing to share what I 
know about how either could be done.

-- 
Terry Jan Reedy



More information about the Python-ideas mailing list