I have the following function that checks a data record to see if it has met certain criteria specified separately in configuration settings. The configurations are set up as a list of dictionaries with certain trigger keywords that are used by the condition check function ('in','not in', etc).
The condition checker has a lot of duplicated code, but it's just different enough that a better setup is not obvious to me. I would appreciate any feedback.
Here is a minimal working example to illustrate:
def check_if_condition_was_met( row, condition ):
condition_met = True
for key, val in condition.iteritems():
if key == 'in':
for condition_key, condition_val in val.iteritems():
if row[condition_key] in condition_val: # IN
continue
else:
condition_met = False
break
elif key == 'not in':
for condition_key, condition_val in val.iteritems():
if row[condition_key] not in condition_val: # NOT IN
continue
else:
condition_met = False
break
elif key == 'max':
for condition_key, condition_val in val.iteritems():
if not row[condition_key]:
condition_met = False
break
if int(row[condition_key]) <= int(condition_val): # MAX (<=)
continue
else:
condition_met = False
break
elif key == 'min':
for condition_key, condition_val in val.iteritems():
if int(row[condition_key]) >= int(condition_val): # MIN (>=)
continue
else:
condition_met = False
break
return condition_met
if __name__ == '__main__':
# data
test_data = [
{'Flag1':'Y', 'Flag2':'Canada','Number':35}
,{'Flag1':'Y', 'Flag2':'United States','Number':35}
,{'Flag1':'N', 'Flag2':'United States','Number':35}
,{'Flag1':'N', 'Flag2':'England','Number':35}
,{'Flag1':'N', 'Flag2':'Canada','Number':35}
,{'Flag1':'N', 'Flag2':'Canada','Number':5}
]
# configuration
test_conditions = [
{ 'in':{'Flag1':['N'], 'Flag2':['United States']} }
,{ 'in':{'Flag1':['Y'],'Flag2':['Canada']}, 'max':{'Number':7} }
,{ 'in':{'Flag1':['Y'],'Flag2':['Canada']}, 'min':{'Number':7} }
,{ 'not in':{'Flag1':['Y']}, 'min':{'Number':7} }
]
for condition_id, condition in enumerate(test_conditions):
print
print 'now testing for condition %i' % condition_id
for data_id, data in enumerate(test_data):
print '%s | %s' % ( data_id, check_if_condition_was_met(data,condition) )