[Python-ideas] Grammar for plus and minus unary ops

Steven D'Aprano steve at pearwood.info
Sat Mar 28 05:13:20 CET 2009

Moved from python-dev to python-ideas.

On Sat, 28 Mar 2009 04:19:46 am Jared Grubb wrote:
> I was recently reviewing some Python code for a friend who is a C++
> programmer, and he had code something like this:
> def foo():
>    try = 0
>    while try<MAX:
>       ret = bar()
>       if ret: break
>       ++try
> I was a bit surprised that this was syntactically valid, 

You shouldn't be. Unary operators are inspired by the equivalent 
mathematical unary operators.

> It appears that the grammar treats the above example as the unary +
> op applied twice:

As it should.

> I'm not a EBNF expert, but it seems that we could modify the grammar
> to be more restrictive so the above code would not be silently valid.
> E.g., "++5" and "1+++5" and "1+-+5" are syntax errors, but still keep
> "1++5", "1+-5", "1-+5" as valid. (Although, '~' throws in a kink...
> should '~-5' be legal? Seems so...)

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*).

Steven D'Aprano

More information about the Python-ideas mailing list