Any solutions you are going to come up with would cause other anomalies such as -(5d) not being equal to -5d. My vote goes to treating + and - as the operators they are and telling people that if they want a negative constant that exceeds the context's precision they're going to have to use Decimal('-N'), rather than adding a terrible hack to the parser (and hence to the language spec).


BTW Do you why the default precision is 28?


On Sun, Mar 9, 2014 at 1:07 PM, Oscar Benjamin <oscar.j.benjamin@gmail.com> wrote:
On 9 March 2014 19:34, Guido van Rossum <guido@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



--
--Guido van Rossum (python.org/~guido)