Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does python parse ++x? [duplicate]

Tags:

python

syntax

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?

like image 358
user1734068 Avatar asked Mar 13 '26 21:03

user1734068


1 Answers

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()))))
like image 194
ecatmur Avatar answered Mar 15 '26 09:03

ecatmur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!