Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why 3 +++ 5 works in Python [duplicate]

In [476]: 3 + 5
Out[476]: 8

In [477]: 3 +++++++++++++++++++++ 5
Out[477]: 8

In [478]: 3 + + + + + + + + + + + 5
Out[478]: 8

In [479]: 3 +++ --- +++ --- +++ 5
Out[479]: 8

Why there is no SyntaxError: invalid syntax or TypeError: bad operand type for unary + error?

I know this handled in compile process, but how it works?

like image 258
Leo Howell Avatar asked Jun 25 '17 07:06

Leo Howell


2 Answers

Using ast module we can create abstract syntax tree presentation and see what happens:

import ast
source = 'ADD SOURCE HERE'
node = ast.parse(source, mode='eval')
ast.dump(node, False, False)

In the case of 3 +++ 5, AST generates the following expression:

'Expression(BinOp(Num(1), Add(), UnaryOp(UAdd(), UnaryOp(UAdd(), Num(2)))))'

Or for example 3 ++ -- 5 produces:

'Expression(BinOp(Num(3), Add(), UnaryOp(UAdd(), UnaryOp(USub(), Num(-5)))))'
like image 99
jsalonen Avatar answered Sep 28 '22 05:09

jsalonen


Beause if there are more than one operator between operand then it will work as below

3 +++ 5  # it will work as 3 + ( + ( +5) )

Hope it clears your doubt.

like image 42
Jay Parikh Avatar answered Sep 28 '22 06:09

Jay Parikh