[Python-ideas] Python Numbers as Human Concept Decimal System
Oscar Benjamin
oscar.j.benjamin at gmail.com
Mon Mar 10 13:12:56 CET 2014
On 10 March 2014 10:59, Steven D'Aprano <steve at pearwood.info> wrote:
> On Mon, Mar 10, 2014 at 10:07:11AM +0000, Oscar Benjamin wrote:
>> On 9 March 2014 20:39, Guido van Rossum <guido at python.org> wrote:
>> > On Sun, Mar 9, 2014 at 1:07 PM, Oscar Benjamin <oscar.j.benjamin at gmail.com> wrote:
>> >>
>> >> 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.
>
> Is that still true? Possibly the peephole optimizer has changed the
> situation?
Yes it does. It also does the same for "complex literals" even though
the language formally only defines imaginary literals. The question is
how to define exactly the grammar. Then once defined if the result is
independent of any context the optimiser can safely constant fold
decimal literals in the same way.
The grammar is here:
http://docs.python.org/3.4/reference/grammar.html
The relevant part is here:
factor: ('+'|'-'|'~') factor | power
power: atom trailer* ['**' factor]
atom: ('(' [yield_expr|testlist_comp] ')' |
'[' [testlist_comp] ']' |
'{' [dictorsetmaker] '}' |
NAME | NUMBER | STRING+ | '...' | 'None' | 'True' | 'False')
So if the specification is that decimal literals go into the NUMBER
part just like int, float and imaginary literals do then the + or -
are at a separate place. The expression -5 ** 2 is evaluated as -(5 **
2) which is -25 rather than (-5) ** 2 which is +25. It may be possible
but it's certainly not straight-forward to rewrite the grammar so that
-25d becomes D('-25') without affecting the normal precedence rules.
>> I think it's reasonable that -(5d) not be equal to -5d.
>
> Did you leave the word "not" out of that sentence? :-)
It's reasonable if you're an experienced user of the decimal module
but yeah okay it's not really reasonable in a general sense...
> I don't think that it is reasonable for -(5d) to not equal -5d. I think
> that's an awful interface, and terribly surprising. I don't think that
> there are any situations were an otherwise redundant pair of parens
> changes behavious. E.g. x*(y) is the same as x*y.
>
> (Parens are sometimes used to disambiguate syntax or change precedence.
> That's different, since the parens aren't redundant.)
>
> Considering that the motivation for this change is to make it easier for
> newbies and numerically naive users, I really do not relish having to
> explain to newbies why -5d and -(5d) are different.
Yes but newbies won't write -(5d). Experts might if it had the
semantics they want. The current behaviour of the Decimal type is
already surprising in this regard so unless __pos__ and __neg__ are
changed there will always be cases that surprise people.
Oscar
More information about the Python-ideas
mailing list