How to pass an operator to a python function?

PythonFunctionPython 2.7

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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: https://stackoverflow.com/questions/1832940/is-using-eval-in-python-a-bad-practice

Solution 3 - Python

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.

Solution 4 - Python

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)

Solution 5 - Python

>>> 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
>>>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionphilshemView Question on Stackoverflow
Solution 1 - PythongrcView Answer on Stackoverflow
Solution 2 - PythonalecxeView Answer on Stackoverflow
Solution 3 - PythonViktor KerkezView Answer on Stackoverflow
Solution 4 - PythonPaul EvansView Answer on Stackoverflow
Solution 5 - PythonamadainView Answer on Stackoverflow