Why 3 +++ 5 works in Python

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 is there no SyntaxError: invalid syntax or TypeError: bad operand type for unary + error?

I know this is handled during compilation, but how does it work?

+5
source share
4 answers

Using the ast module, we can create an abstract representation of the syntax tree 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)))))' 
+6
source

Avoid if there is more than one operator between the operand, then it will work as below

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

Hope it clears your doubts.

+5
source
 + obj 

will call unary __pos__(self) (as well as - obj calls __neg__(self) ). Repeatable + and - until obj will call them repeatedly.

 ++++++-+++++ 5 # = -5 

in your expression

 3 +++++++++++++++++++++ 5 

the leftmost statement will call binary __add__ (or __sub__ ). therefore, there is no ambiguity and there is no reason for this to cause an error.

the python interpreter does not optimize these calls (which is probably due to the fact that you can overload __pos__ and __neg__ to do whatever you want ...):

 from dis import dis def f(x, y): return x ++--++ y dis(f) 

prints:

  4 0 LOAD_FAST 0 (x) 3 LOAD_FAST 1 (y) 6 UNARY_POSITIVE 7 UNARY_POSITIVE 8 UNARY_NEGATIVE 9 UNARY_NEGATIVE 10 UNARY_POSITIVE 11 BINARY_ADD 12 RETURN_VALUE 
+2
source

The expression is the same as:

3 + (+ (+ 5))

Any numerical expression may be preceded by making it negative:

 5-(-(3)) = 5-(-3) = 5+3 = 8 

and

 5-(-(-3)) = 5-(3) = 2 

Python does not have increment operators like ++ and --

in C, which was probably the source of your confusion. To increase or decrease the variable i or j in Python, use this style:

 i += 1 j -= 1 
+1
source

Source: https://habr.com/ru/post/1269192/


All Articles