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

Oscar Benjamin oscar.j.benjamin at gmail.com
Sun Mar 9 21:07:39 CET 2014


On 9 March 2014 19:34, Guido van Rossum <guido at python.org> wrote:
>
> I hope that somebody will take up the task to write a PEP about introducing
> a decimal literal; that sounds like an obtainable goal, less controversial
> than changing Decimal(<float>).

I said I'd have a go at this. It's not as simple as it might seem though.

The simplest proposal would be to say that 3.14d is equivalent to
Decimal('3.14'). The fact the the constructor is independent of the
context is good here. It means that the value of the literal can be
determined statically which is good for trying to understand what code
does and also for constant folding etc.

The problem though is with things like +3.14d or -3.14d. Python the
language treats the + and - signs as not being part of the literal but
as separate unary operators. This is unimportant for int, float and
imaginary literals because there unary + is a no-op and unary - is
exact. For decimal this is not the same as +Decimal('3.14') is not the
same as Decimal('+3.14'):

    >>> from decimal import Decimal, getcontext
    >>> getcontext().prec = 3
    >>> Decimal('+1234')  # Exact
    Decimal('1234')
    >>> +Decimal('1234')  # Rounded
    Decimal('1.23E+3')
    >>> Decimal('-1234')  # Exact
    Decimal('-1234')
    >>> -Decimal('1234')  # Rounded
    Decimal('-1.23E+3')

I think that this behaviour would be surprising from a literal. I
would prefer to be able to say that -1234d was equivalent to
Decimal('-1234d') and would be guaranteed not to round. I just don't
really know if that's trivially easy or really difficult given the
current grammar specification and parse/compiler infrastructure.


Oscar


More information about the Python-ideas mailing list