If you are only comparing numerical values this approach would be safer in general.
This could also be made to work for non-numerical values.
from operator import gt, ge, lt, le, eq, ne
def compare(expression):
parts = expression.split()
if len(parts) != 3:
raise Exception("Can only call this with 'A comparator B', like 1 > 2")
a, comp, b = parts
try:
a, b = float(a), float(b)
except:
raise Exception("Comparison only works for numerical values")
ops = {">": gt, '<': lt, '>=': ge, '<=': le, '==': eq, '!=': ne}
if comp not in ops:
raise Exception("Can only compare with %s" % (", ".join(ops)))
return ops.get(comp)(a, b)
def run_comp(expression):
try:
print("{} -> {}".format(expression, compare(expression)))
except Exception as e:
print str(e)
if __name__ == "__main__":
run_comp("1.0 > 2")
run_comp("2.0 > 2")
run_comp("2 >= 2")
run_comp("2 <= 1")
run_comp("5 == 5.0")
run_comp("5 <= 5.0")
run_comp("5 != 5.0")
run_comp("7 != 5.0")
run_comp("pig > orange")
run_comp("1 ! 2")
run_comp("1 >")
OUTPUT
1.0 > 2 -> False
2.0 > 2 -> False
2 >= 2 -> True
2 <= 1 -> False
5 == 5.0 -> True
5 <= 5.0 -> True
5 != 5.0 -> False
7 != 5.0 -> True
Comparison only works for numerical values
Can only compare with >=, ==, <=, !=, <, >
Can only call this with 'A comparator B', like 1 > 2