The Python Oracle

How to pass an operator to a python function?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Lost Civilization

--

Chapters
00:00 How To Pass An Operator To A Python Function?
00:24 Answer 1 Score 14
00:49 Accepted Answer Score 109
01:02 Answer 3 Score 1
01:15 Answer 4 Score 59
01:43 Thank you

--

Full question
https://stackoverflow.com/questions/1859...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #function #python27

#avk47



ACCEPTED ANSWER

Score 109


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



ANSWER 2

Score 59


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?




ANSWER 3

Score 14


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.




ANSWER 4

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