-2

Is there a way to eval the comparison where the comparison operator is passed as string. without doing alot of if-else's. F.e.

 def cmp(arg1, op, arg2) : ......

and then :

 cmp(5, "==", 6)
 cmp(7, ">", 6)
 cmp(12, "<=", 34)
 cmp("abc", "==", "bad")
sten
  • 7,028
  • 9
  • 41
  • 63
  • 2
    You could use eval or, better, a mapping to operator functions. Did you try anything? What happened? – jonrsharpe Jun 14 '17 at 20:59
  • but doesn't this mean that I have to convert it to string... and then I have other type of more complex classes to compare. – sten Jun 14 '17 at 21:06
  • Convert what to string? E.g. `"=="` is *already a string*. And what *"more complex classes"* ; don't they implement `__eq__`? – jonrsharpe Jun 14 '17 at 21:07
  • (6,"==", 7) ==> "6 == 7" – sten Jun 14 '17 at 21:09
  • Oh, I see. You do to use `eval`, that's one of the reasons I said the second suggestion was better. – jonrsharpe Jun 14 '17 at 21:10
  • and I can't convert (BlahX, "==", BooY) ==> "BlahX == BooY", won't work. – sten Jun 14 '17 at 21:14
  • If they have a working `__repr__` you can make a string that evaluates just fine with little effort, but again *building a mapping is better*. Did you do *any* research? For example https://stackoverflow.com/questions/18591778/how-to-pass-an-operator-to-a-python-function – jonrsharpe Jun 14 '17 at 21:15
  • thanks for the link , one of the answers worked out – sten Jun 14 '17 at 21:31

1 Answers1

7

You should avoid using eval, use operator module instead.

import operator
ops = {
    '<': operator.lt,
    '<=': operator.le,
    '==': operator.eq,
    '!=': operator.ne,
    '>=': operator.ge,
    '>': operator.gt
}

def cmp(arg1, op, arg2):
    operation = ops.get(op)
    return operation(arg1, arg2)
Micky Loo
  • 1,433
  • 9
  • 7