Python expression evaluator and Interpreter pattern
Question: I am trying to implement a simple expression evaluator in python,but I am
stuck in parser method.Below is my code snippet.

    
    
        class Number:
        def __init__(self,value):
            self.value=value
        def execute(self):
            return self.value
    
    class Plus:
        def __init__(self,left,right):
            self.left=left
            self.right=right
        def execute(self):
            return self.left+self.right
    
    class Minus:
        def __init__(self,left,right):
            self.left=left
            self.right=right
        def execute(self):
            return self.left-self.right
    
    class Multiply:
        def __init__(self,left,right):
            self.left=left
            self.right=right
        def execute(self):
            return self.left*self.right
    import re
    def parser(input):
        stack=[]
        token_pat = re.compile("\s*(?:(\d+)|(.))")
        for number, operator in token_pat.findall(input):
    
    
            if number:
                stack.append(Number(int(number)))
    
            else:
                first,second=stack.pop(),stack.pop()
    
                if operator=="+":
                    stack.append(Plus(first,second))
                elif operator=="-":
                    stack.append(Minus(first,second))
                elif operator=="*":
                    stack.append(Multiply(first,second))
                else:
                    raise SyntaxError("unknown operator")
        print stack[0].execute()
    
    
    if __name__=="__main__":
        parser('1 2 +')
    

When I am running the above code,I am getting following error.Can anybody
review my code .

    
    
    Traceback (most recent call last):
      File "Interpreter.py", line 52, in <module>
        parser('1 2 +')
      File "Interpreter.py", line 48, in parser
        print stack[0].execute()
      File "Interpreter.py", line 12, in execute
        return self.left+self.right
    TypeError: unsupported operand type(s) for +: 'instance' and 'in
    


Answer: The error message is that confusing because you're using [classic
classes](http://docs.python.org/reference/datamodel.html#new-style-and-
classic-classes). With new-style classes (i.e. inheriting from `object`), you
get a much more reasonable:

    
    
    TypeError: unsupported operand type(s) for +: 'Number' and 'Number'
    

Either use `int`s instead of Number objects, or implement adding logic by
implementing [`__add__` and
friends](http://docs.python.org/reference/datamodel.html#object.__add__), or
add evaluating logic in `Plus.execute`.

Also note that you're reimplementing Python's built-ins. Additionally, having
an `execute` method is pretty much an anti-pattern. A much shorter
implementation would be

    
    
    import functools,operator,re
    
    def parser(inp):
        stack=[]
        token_pat = re.compile("\s*(?:(\d+)|(.))")
        for number, op in token_pat.findall(inp):
            if number:
                stack.append(functools.partial(lambda i:i, int(number)))
            else:
                first,second=stack.pop(),stack.pop()
                try:
                    op = {
                        '+': operator.add,
                        '-': operator.sub,
                        '*': operator.mul
                    }[op]
                except KeyError:
                    raise SyntaxError("unknown operator")
    
                stack.append(functools.partial(lambda op,first,second:
                            op(first(), second()), op, first, second))
        print(stack[0]())
    
    if __name__=="__main__":
        parser('1 2 + 3 *')
    

