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.
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
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,'>')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With