Search code examples
pythonpython-3.xoperators

Contiguous operators in Python raises no error


Accidentally, I typed multiple contiguous + operators and it ran successfully. This is what I did

2 ++ 3 // returns 5

Then i tried multiple combinations and it actually executes only the last operator

2 +++-3 // returns -1

This is somewhat strange to me. Shouldn't it just raise syntax error. Any details or related information will be helpful. Why did they choose to be it like that?

I am running Python3.10.4. Might have different behavior on other versions. I know its not a pure programming problem but it do related to system design. What was the intention or need to do this?


Solution

  • What's happening here is that you have chosen a set of operators that work in both binary and unary use cases. The first operator in the sequence is taken as the binary operator and the rest are taken as unary operators on the right operand. The extra operators are essentially just multiplying the right operand by +1 or -1.

    # Positive 3 - like multiplying by +1
    +3
    # Negative 3 - like multiplying by -1
    -3
    

    The below code boils down to 2 + (positive 3)

    2 ++ 3 # Equivalent to 2 + (+3)
    

    The example after that boils down to 2 + (+(+(-3))). Which is just 2-3 = -1

    2 +++-3 # Equivalent to 2 + (+(+(-3)))
    

    Notice when you do something like this with * because it is taken as a unary operator and * does not actually have an unary application, you get a syntax error:

    2 +*- 3 # Equivalent to 2 + (*(-3))) which makes no sense to the interpreter, what's (*3)?
    

    But this would be okay:

    2*+-3 # Equivalent to 2 * (+(-3))
    

    because here * is first so it is taken as the binary operator. The expression boils down to 2 * (+(-3))) or 2 * (-3) = -6