3

Possible Duplicate:
Behaviour of increment and decrement operators in Python

Completely new to python I wrote ++x thinking it would increment x. So I was wrong about that, no problem. But no syntax error either. Hence my question: what does ++x actually mean in python?

Community
  • 1
  • 1

1 Answers1

4

The + operator is the unary plus operator; it returns its numeric argument unchanged. So ++x is parsed as +(+(x)), and gives x unchanged (as long as x contains a number):

>>> ++5
5
>>> ++"hello"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary +: 'str'

If + is called on an object of a user-defined class, the __pos__ special method will be called if it exists; otherwise, TypeError will be raised as above.

To confirm this we can use the ast module to show how Python parses the expression:

import ast
print(ast.dump(ast.parse('++x', mode='eval')))
Expression(body=UnaryOp(op=UAdd(), operand=UnaryOp(op=UAdd(), operand=Name(id='x', ctx=Load()))))
ecatmur
  • 152,476
  • 27
  • 293
  • 366
  • Thank you, really useful answer, particularly the tip about using the ast module. My immediate reaction to "it returns its numeric argument unchanged" was: so what's the point? But I guess people will find uses for it with user-defined classes. – user1734068 Oct 12 '12 at 09:25