65

I'd like to pass a math operator, along with the numeric values to compare, to a function. Here is my broken code:

def get_truth(inp,relate,cut):    
    if inp print(relate) cut:
        return True
    else:
        return False

and call it with

get_truth(1.0,'>',0.0)

which should return True.

jonrsharpe
  • 107,083
  • 22
  • 201
  • 376
philshem
  • 23,689
  • 7
  • 58
  • 120

5 Answers5

91

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
grc
  • 21,645
  • 4
  • 39
  • 63
51

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?

Michael Dorner
  • 14,449
  • 11
  • 73
  • 105
alecxe
  • 441,113
  • 110
  • 1,021
  • 1,148
12

Use the operator module. It contains all the standard operators that you can use in python. Then use the operator as a functions:

import operator

def get_truth(inp, op, cut):
    return op(inp, cut):

get_truth(1.0, operator.gt, 0.0)

If you really want to use strings as operators, then create a dictionary mapping from string to operator function as @alecxe suggested.

Viktor Kerkez
  • 41,890
  • 11
  • 100
  • 83
-1

Use the operator module instead:

import operator
def get_truth(inp, relate, cut):
    rel_ops = {
        '>': operator.gt,
        '<': operator.lt,
        '>=': operator.ge,
        '<=': operator.le,
        '==': operator.eq,
        '!=': operator.ne
    }
    return rel_ops[relate](inp, cut)
E_net4 - Krabbe mit Hüten
  • 24,143
  • 12
  • 85
  • 121
Paul Evans
  • 26,798
  • 3
  • 34
  • 52
-3
>>> def get_truth(inp,relate,cut):
...     if eval("%s%s%s" % (inp,relate,cut)):
...         return True
...     else:
...         return False
...
>>> get_truth(1.0,'>',0.0)
True
>>>
amadain
  • 2,516
  • 3
  • 36
  • 52