Dynamic comparison operators
Tim Chase
python.list at tim.thechases.com
Thu May 24 10:42:06 EDT 2012
On 05/24/12 09:32, Phil Le Bienheureux wrote:
>> I would like to pass something like this into a function
>> test(val1,val2,'>=')
>
> You can pass an operator as an argument to your function.
>
> See :
> http://docs.python.org/library/operator.html
And if you want to use strings, you can map them to the functions:
import operator as o
OPERATOR_MAP = {
'=': o.eq,
'==': o.eq,
'!=': o.ne,
'>=': o.ge,
# ...
}
def test(v1, v2, op):
return OPERATOR_MAP[op](v1, v2)
-tkc
More information about the Python-list
mailing list