[Python-Dev] surprised to "++" and "--"

Matthew Wilkes matthew at matthewwilkes.co.uk
Fri Sep 25 12:58:46 CEST 2009


>     I know that there is no "++" or "--" operator in python, but if  
> "var++" or something like that in my code(you know, most of C/C++  
> coders may like this),there is nothing wrong reported and program  
> goes on just like expected!!
>     This is obscure, maybe a bug.

Hi,

Firstly, this list is for the development of Python, not with Python,  
questions about problems you're having should generally go to the  
users' list.  Bug reports should go to the bug tracker at http://bugs.python.org/

However, in this particular case, there's no point submitting it; you  
have made a mistake somewhere.  As you say, there is no ++ or -- unary  
postfix operator, but this DOES raise a SyntaxError:

> >>> var = 1
> >>> var++
>   File "<stdin>", line 1
>     var++
>         ^
> SyntaxError: invalid syntax


The prefix form is valid, as + and - are both valid prefix unary  
operators:

> >>> ++var
> 1
> >>> --var
> 1

Which are equivalent to:

> >>> +(+1)
> 1
> >>> -(-1)
> 1
>

If you were to try this with something that didn't implement __neg__  
and __pos__, such as strings, you'd get:

> >>> ++var
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: bad operand type for unary +

Hope this clarifies things for you,

Matthew


More information about the Python-Dev mailing list