Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

operator python parameter

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.

like image 286
Izabela Avatar asked Nov 09 '12 14:11

Izabela


2 Answers

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
like image 74
Michael Mauderer Avatar answered Oct 10 '22 09:10

Michael Mauderer


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,'>')
like image 34
Artsiom Rudzenka Avatar answered Oct 10 '22 08:10

Artsiom Rudzenka