How to pass an operator to a python function?
Have a look at the operator module:
import operator
get_truth(1.0, operator.gt, 0.0)
...
def get_truth(inp, relate, cut):
return relate(inp, cut)
# you don't actually need an if statement here
Make a mapping of strings and operator functions. Also, you don't need if/else condition:
import operator
def get_truth(inp, relate, cut):
ops = {'>': operator.gt,
'<': operator.lt,
'>=': operator.ge,
'<=': operator.le,
'==': operator.eq}
return ops[relate](inp, cut)
print(get_truth(1.0, '>', 0.0)) # prints True
print(get_truth(1.0, '<', 0.0)) # prints False
print(get_truth(1.0, '>=', 0.0)) # prints True
print(get_truth(1.0, '<=', 0.0)) # prints False
print(get_truth(1.0, '==', 0.0)) # prints False
FYI, eval()
is evil: Why is using 'eval' a bad practice?