76

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.

0

5 Answers 5

104

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
4
  • In the end, I just got rid of my function and used operator. 'if operator.gt(1.0,0.0):'
    – philshem
    Sep 3, 2013 at 12:43
  • Couldn't you just use if 1.0 > 0.0:?
    – grc
    Sep 3, 2013 at 13:38
  • 4
    I want to be able to change the operator dynamically (so I may have to go back to the function solution).
    – philshem
    Sep 3, 2013 at 15:28
  • 1
    for in operator see operator.contains(a,b). Note that this checks presence of b in a not the other way round. Sep 25, 2018 at 14:28
58

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?

3
  • 3
    +1. Also, this answer demonstrates that you can directly return the value of ops[relate], instead of explicitly testing it and returning a literal True or False.
    – chepner
    Sep 3, 2013 at 12:05
  • 1
    I recommend to replace = with ==
    – leoll2
    Mar 12, 2021 at 15:39
  • Beautiful! But please use == for comparison! Jun 14, 2021 at 6:58
13

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.

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)
2
-4
>>> 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
>>>
4

Not the answer you're looking for? Browse other questions tagged or ask your own question.