Array of functions, Pythonically

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • MartinRinehart@gmail.com

    Array of functions, Pythonically

    My parser has found an expression of the form CONSTANT_INTEGE R
    OPERATOR CONSTANT_INTEGE R. I want to fold this into a single
    CONSTANT_INTEGE R.

    The OPERATOR token has an intValue attribute, '+' == 0, '-'== 1, etc.
    In C I'd put functions Add, Subtract, ... into an array and call
    ArithmeticFunct ions[ 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?
  • castironpi@gmail.com

    #2
    Re: Array of functions, Pythonically

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

    Then EXPR OPER EXPR -ops[ OPER ]( EXPR, EXPR ), right?

    Comment

    • Paul McGuire

      #3
      Re: Array of functions, Pythonically

      On Feb 25, 11:53 am, castiro...@gmai l.com wrote:
       { '+': operator.add, '-': operator.sub, ... }
      >
      Then EXPR OPER EXPR -ops[ OPER ]( EXPR, EXPR ), right?
      I think this is the most Pythonic idiom. You can even define your own
      custom binary operators, such as '$' to convert dollars and cents to a
      float:
      >>ops = { '+': operator.add, '-': operator.sub, '$' : lambda a,b: a + b/100.0 }
      >>ops['$'](1,2) # convert dollars and cents to float
      1.02

      -- Paul

      Comment

      Working...