Many operators between operands

Can someone explain why the Python interpreter (2.7.3) gives the following:

>>> 5 -+-+-+ 2

3

How useful and for what purpose?

+5
source share
4 answers

You can use dishere to see how the expression was actually evaluated:

In [29]: def func():
   ....:     return 5 -+-+-+ 2
   ....: 

In [30]: import dis

In [31]: dis.dis(func)
  2           0 LOAD_CONST               1 (5)
              3 LOAD_CONST               2 (2)
              6 UNARY_POSITIVE      
              7 UNARY_NEGATIVE      
              8 UNARY_POSITIVE      
              9 UNARY_NEGATIVE      
             10 UNARY_POSITIVE      
             11 BINARY_SUBTRACT     
             12 RETURN_VALUE        

So this expression is equivalent to this:

In [32]: 5 - (+(-(+(-(+(2))))))
Out[32]: 3
+10
source

It's just equal

5 - (+(-(+(-(+2)))))

where all + and - outside the first are unary operators. For numbers, +returns the operand unchanged. But its value can be redefined using a special method __pos__on your own classes.

, , ( ), __neg__ / __pos__.


, C-like pre-increment -- ++. .

class IncrementableInteger(object):
    def __init__(self, val=0):
        self.val = val
    def __pos__(self):
        class PlusOne:
            def __pos__(_self):
                self.val += 1
        return PlusOne()
    def __neg__(self):
        class MinusOne:
            def __neg__(_self):
                self.val -= 1
        return MinusOne()
    def __str__(self):
        return str(self.val)
    def __repr__(self):
        return repr(self.val)

:

>>> IncrementableInteger(4)
4
>>> v=_
>>> ++v
>>> v
5
+6

Except that I am confusing the code, I see no utility.

Evaluation of this:

5 -+-+-+ 2 = 5 -(+(-(+(-(+ 2)))))
           = 5 -(+(-(+(- 2))))
           = 5 -(+(-(- 2)))
           = 5 -(+(+ 2))
           = 5 -(+ 2)
           = 5 - 2
           = 3
+3
source

This is interpreted as follows:

5 - (+(-(+(-(+2)))))

You are allowed to write -ato get a negative sign a. For symmetry and "Why not?" you should also use the plus sign prefix, for example +a.

Adding multiple characters is not very useful, but it is allowed, perhaps because it is simply legal in the grammar, and no one saw the need to explicitly prohibit it.

+2
source

All Articles