[Python-ideas] Grammar for plus and minus unary ops
Jared Grubb
jared.grubb at gmail.com
Sat Mar 28 20:26:33 CET 2009
On 27 Mar 2009, at 21:13, Steven D'Aprano wrote:
>>
>> I was a bit surprised that this was syntactically valid,
>
> You shouldn't be. Unary operators are inspired by the equivalent
> mathematical unary operators.
> .....
> Why would we want to do this? I'm sure there are plenty of other
> syntax
> constructions in Python which just happen to look like something from
> other languages, but have a different meaning. Do we have to chase our
> tails removing every possible syntactically valid string in Python
> that
> has a different meaning in some other language? Or is C++ somehow
> special that we treat it differently from all the other languages?
>
> Not only is this a self-inflicted error (writing C++ code in a Python
> program is a PEBCAK error), but it's rare: it only affects a minority
> of C++ programmers, and they are only a minority of Python
> programmers.
> There's no need to complicate the grammar to prevent this sort of
> error. Keep it simple. ---1 on the proposal (*grin*).
It *was* a surprise. Of the languages I've used in my life (BASIC, C, C
++, Java, Javascript, Perl, PHP, and Python), only two would treat
prefix ++ as double unary plus (and I try to forget BASIC as best I
can :) ). I remember when I first picked up Python, I wrote "i++" once
(I think many beginning Python programmers do), and I was grateful
that a syntax error popped up (rather than silently doing nothing) and
I never did it again... So, now, a few years later I was reviewing
code that had "++i" in it (from a new Python developer), and did a
double-take on the code and had a moment of surprise that it had even
run at all.
As a devil's advocate: any code that requires double-unary plus is
probably either abusing operator overloading or is abusing the eval
keyword. It seems that adding a restriction to the grammar would
probably be more helpful than harmful (the workaround for the alien
case, if there is one, of needing double-unary plus would be to use
parens: "+(+x)").
In any case, I understand that dynamic languages are going to allow
for side effects to occur anywhere, so it's tough to remove it. I'm
actually only +0 on it as it is... Just a "nice" feature I thought I'd
throw out there.... :)
Jared
More information about the Python-ideas
mailing list