Python Interpreter Behavior?
Question: I am using Python 2.7.

This is what happened:

    
    
    >>> 2+++2
    4
    

I am not sure as to how the python interpreter interprets this expression.

The only reason I can come up with is that successive "+" after the first "+"
are considered as unary operators and the first "+" is considered as a binary
operator, but what is actually the mechanism that is happening I am not sure
of.

I would want someone to answer the question in terms of the grammar specifics
of Python programming language and also report some other ambiguous
expressions. I came up with some other expressions which are listed below
(with their results):

    
    
    >>> 2------------2
    4
    >>> 2+-2+-2+-2+-2+-2-------------------------2
    -10
    


Answer: You're right; Python is interpreting this as `2 + (++2)`, as you might expect.
You can see this by looking at the compiled bytecode for 2+2 and 2+++2, as
follows:

    
    
    >>> dis.dis(lambda: 2+2)
      1           0 LOAD_CONST               2 (4)
                  3 RETURN_VALUE        
    >>> dis.dis(lambda: 2+++2)
      1           0 LOAD_CONST               1 (2)
                  3 LOAD_CONST               1 (2)
                  6 UNARY_POSITIVE      
                  7 UNARY_POSITIVE      
                  8 BINARY_ADD          
                  9 RETURN_VALUE    
    

* * *

You might want to know why Python parses 2+++2 like this. First, the code gets
split up into tokens:

    
    
    >>> from cStringIO import StringIO
    >>> import tokenize
    >>> tokenize.generate_tokens(StringIO("2+++2").readline)
      9 <generator object generate_tokens at 0x0000000007BC7480>
    >>> list(tokenize.generate_tokens(StringIO("2+++2").readline))
      10 
    [(2, '2', (1, 0), (1, 1), '2+++2'),
     (51, '+', (1, 1), (1, 2), '2+++2'),
     (51, '+', (1, 2), (1, 3), '2+++2'),
     (51, '+', (1, 3), (1, 4), '2+++2'),
     (2, '2', (1, 4), (1, 5), '2+++2'),
     (0, '', (2, 0), (2, 0), '')]
    

It's the parser that then associates the list of tokens into a syntax tree:

    
    
    >>> st = ast.parse("2+++2")
    >>> st
      36 <_ast.Module at 0x7d2acc0>
    >>> ast.dump(st)
      37 'Module(body=[Expr(value=BinOp(left=Num(n=2), op=Add(), right=UnaryOp(op=UAdd(), operand=UnaryOp(op=UAdd(), operand=Num(n=2)))))])'
    

This follows standard disambiguation rules.

