Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally set a relational operator in Python

Tags:

python

I wish to create a function which filters a data set, and I wish to pass into that function the logic of whether to search <, > or ==.

Is there a preferred method for this in Python, or do I need to create 3 different unique code bases for each using elif for example

if rel_operator == "gt":
    print("GT OPERATION")
elif rel_operator == "lt":
    print("LT OPERATION")
elif rel_operator == "eq":
    print("EQ OPERATION")
like image 402
Single Entity Avatar asked Aug 10 '26 18:08

Single Entity


2 Answers

You can use python's built-in operator module:

< corresponds to operator.lt

> corresponds to operator.gt 
# I was hasty in writing le in my comment

== corresponds to operator.eq

Following @Nick A comment you can do this:

d = {'gt': operator.gt.__doc__,
'lt':operator.lt.__doc__,
'eq':operator.eq.__doc__}

rel_operator = 'gt'
d.get(rel_operator)

'gt(a, b) -- Same as a>b.'
like image 154
gold_cy Avatar answered Aug 12 '26 07:08

gold_cy


As already mentioned in the comments and the other answer you can use the operator module which wraps the comparison operators as callables.

In case you want to pass in a string you could simply get the appropriate callable with getattr:

import operator

rel_operator = "gt"  # for example
real_rel_operator = getattr(operator, rel_operator)

and then call the real_rel_operator with the values as arguments. That works because your strings are already what the functions are called. No need to create a dictionary in this case.

like image 34
MSeifert Avatar answered Aug 12 '26 07:08

MSeifert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!