Using an operator as an object

Alex Martelli aleax at aleax.it
Mon Mar 3 04:33:30 EST 2003


Tony C wrote:

> Does Python have the ability to pass an operator (+,/,- etc) as an
> object (not a string), so I don't have to use an if for each operator
> , as in the first function below ?

As Eric already indicated in responding to you, operators are
also available as functions from module operator in the standard
Python library.  However, if you DO have a string representing
an operator, an if/elif tree is still not the best way to find
out which one of the functions in module operator you have to
call -- rather, you're probably better off building a dictionary
once only:

import operator
string_to_op = {
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul,
    '/': operator.div,
    '%': operator.mod,
    # and possibly others if you need them, of course
}

and then:

def docalc(op_as_string, num1, num2):
    return string_to_op[op_as_string](num1, num2)


Alex





More information about the Python-list mailing list