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
If you're going to use such a map, why not map directly to functions instead of having a layer of indirection by name? For example:
symbol_func_map = {
'<': (lambda x, y: x < y),
'<=': (lambda x, y: x <= y),
'==': (lambda x, y: x == y),
#...
}
While this wouldn't be any more concise than your current implementation, it should get the correct behaviour in the majority of cases. The remaining problems are where a unary and a binary operator conflict, and those could be addressed by adding arity to the dictionary keys:
symbol_func_map = {
('<', 2): (lambda x, y: x < y),
('<=', 2): (lambda x, y: x <= y),
('==', 2): (lambda x, y: x == y),
('-', 2): (lambda x, y: x - y),
('-', 1): (lambda x: -x),
#...
}