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

Terry Reedy tjreedy at udel.edu
Sat Mar 28 00:49:45 CET 2009

>> I was recently reviewing some Python code for a friend who is a C++ 
>> programmer, and he had code something like this:
>> def foo():
>>  attempt = 0
>>  while attempt<MAX:
>>     ret = bar()
>>     if ret: break
>>     ++attempt
>> I was a bit surprised that this was syntactically valid, and because 
>> the timeout condition only occurred in exceptional cases, the error 
>> has not yet caused any problems.

A complete test suite would include such a case ;-).

>> It appears that the grammar treats the above example as the unary + op 
>> applied twice:
>> u_expr ::=
>>             power | "-" u_expr
>>              | "+" u_expr | "\~" u_expr
>> Playing in the interpreter, expressions like "1+++++++++5" and 
>>  "1+-+-+-+-+-+-5" evaluate to 6.
>> 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...)


1) This would be a petty, gratuitous restriction that would only 
complicate the language and make it harder to learn for no real gain.

2) It could break code.  + ob maps to type(ob).__pos__(ob), which could 
do anything, and no necessary just return ob as you are assuming.

3) Consider eval('+' + somecode).  Suppose somecode happens to start 
with '+'.  Currently the redundancy is harmless if not meaningful.

In summary, I think the following applies here:
"Special cases aren't special enough to break the rules."

Terry Jan Reedy

More information about the Python-ideas mailing list