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?

1
  • 1
    you're probably looking for x += 1
    – monkut
    Oct 10, 2012 at 8:06

1 Answer 1

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()))))
1
  • 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. Oct 12, 2012 at 9:25

Not the answer you're looking for? Browse other questions tagged or ask your own question.