Array of functions, Pythonically

Duncan Booth duncan.booth at invalid.invalid
Mon Feb 25 09:56:02 EST 2008


MartinRinehart at gmail.com wrote:

> My parser has found an expression of the form CONSTANT_INTEGER
> OPERATOR CONSTANT_INTEGER. I want to fold this into a single
> CONSTANT_INTEGER.
> 
> The OPERATOR token has an intValue attribute, '+' == 0, '-'== 1, etc.
> In C I'd put functions Add, Subtract, ... into an array and call
> ArithmeticFunctions[ intValue ] to perform the operation. Would I
> index into a list of functions in Python, or would IF/ELIF/ELIF ... be
> the way to go?
> 
Well, you could add another attribute to the OPERATOR token:

   token.operation = operator.add

or you could have an a list of operations keyed in token.intValue:

 [ operator.add, operator.sub, ...]

or you could use a dictionary (that intValue attribute is just so C):

 { '+': operator.add, '-': operator.sub, ... }

I don't know the structure of your program, but I'd go for subclassing 
your operator. So you would have classes OperatorAdd, OperatorSub, etc. 
and then you can make the operation a method of the class. Seomthing 
like:

   class Token(object): ...
       def foldConstants(self): pass

   class Operator(Token): ...
       def foldConstants(self):
          self.left.foldConstants()
          self.right.foldConstants()
          if self.left.isConstant and self.right.isConstant:
              self.value, self.isConstant = self.doFold()


   class OperatorAdd(Operator): ...
       def doFold(self):
           return self.left.value + self.right.value, True



More information about the Python-list mailing list