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

Bruce Leban bruce at leapyear.org
Sat Mar 28 04:16:05 CET 2009


If you want to make sure that you can't use ++ or --, then target that
directly: add ++ and -- as tokens to the language and make them always
illegal. While that might be a bit of a kludge, I think it's far better than
adding a complicated rule that you can't put two + or two - in a row.

And if you're worried about eval('+' + somecode), you've got three choices:
(1) leave out the '+' because it has no effect; (2) write eval('+ ' +
somecode) and (3) are you sure you really want to use eval?

--- Bruce

On Fri, Mar 27, 2009 at 4:49 PM, Terry Reedy <tjreedy at udel.edu> 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():
>>>  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
>
> 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
>
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20090327/727c1fc0/attachment.html>


More information about the Python-ideas mailing list