7

In Python, how can I pass an operator like + or < as a parameter to a function which expects a comparison function as a parameter?

def compare (a,b,f):
    return f(a,b)

I have read about functions like __gt__() or __lt__() but still I was not able to use them.

3 Answers 3

12

The operator module is what you are looking for. There you find functions that correspond to the usual operators.

e.g.

operator.lt
operator.le
Sign up to request clarification or add additional context in comments.

Comments

5

use operator module for this purposes

import operator
def compare(a,b,func):

    mappings = {'>': operator.lt, '>=': operator.le,
                '==': operator.eq} # and etc. 
    return mappingsp[func](a,b)

compare(3,4,'>')

2 Comments

Why the lambda? Don't you just want {'>':operator.lt, '>=':operator.le, ... }
just forget to check without +1 for your comment
0

Use a lambda condition as a method parameter:

>>> def yourMethod(expected_cond, param1, param2):
...     if expected_cond(param1, param2):
...             print 'expected_cond is true'
...     else:
...             print 'expected_cond is false'
... 
>>> condition = lambda op1, op2: (op1 > op2)
>>> 
>>> yourMethod(condition, 1, 2)
expected_cond is false
>>> yourMethod(condition, 3, 2)
expected_cond is true
>>> 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.