-1

I have some KPIs and for some, beyond the target value is good while for others it's bad.

Can I do something like

comparator = '<'
value = 100
target = 200

and then go on to say

value comparator target

So that python sees this as 100 < 200 and returns True?

For context, I have a table of KPIs which follow the format:

KPI1: < 100 On Target, > 110 Action Required

KPI2: > 50 On Target, <

and I plan to loop through them and through their associated data to apply RAG ratings.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Johnny
  • 1

2 Answers2

0

You can use first-class methods. This allows you to skip importing the operator module, and is safer than using eval():


def lt(a, b): return a < b
def gt(a, b): return a > b
def eq(a, b): return a == b

comparator = lt
print(comparator(4, 5))  # >>> True

Michael Bianconi
  • 5,072
  • 1
  • 10
  • 25
-2

This can work (using eval)

comparator_1  = '>'
x = 7
y = 12
print(eval('{} {} {}'.format(x,comparator_1,y)))
comparator_2  = '<'
print(eval('{} {} {}'.format(x,comparator_2,y)))

output

False
True
balderman
  • 22,927
  • 7
  • 34
  • 52