Array of functions, Pythonically

Paul McGuire ptmcg at austin.rr.com
Mon Feb 25 13:03:00 EST 2008


On Feb 25, 11:53 am, castiro... at gmail.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



More information about the Python-list mailing list