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?
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)))))'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With