I need a function which takes one of python\'s operator symbols or keywords as a string, along with its operands, evaluates it, and returns the result. Like
You could use eval to generate lambda functions for the operators instead of using the operator module. Eval is generally bad practice, but I think for this purpose it's fine because it's nothing really crazy.
def make_binary_op(symbol):
return eval('lambda x, y: x {0} y'.format(symbol))
operators = {}
for operator in '+ - * / ^ % (etc...)'.split(' '):
operators[operator] = make_binary_op(operator)
operators['*'](3, 5) # == 15