Dynamic comparison operators

Colin J. Williams cjw at ncf.ca
Thu May 24 11:22:37 EDT 2012


On 24/05/2012 10:14 AM, mlangenhoven at gmail.com wrote:
> I would like to pass something like this into a function
> test(val1,val2,'>=')
>
> and it should come back with True or False.
>
> Is there a way to dynamically compare 2 values like this or will I have to code each operator individually?

Would something like the following meet your need?

Yes, it would be nice if there were a b.__name__ constant.

Colin W.
'''
I would like to pass something like this into a function
test(val1,val2,'>=')

and it should come back with True or False.

Is there a way to dynamically compare 2 values like this or will I have 
to code each operator individually?
'''
def test(text):
     return eval(text)

a= 25
b= 50

print test('a == b')
print test('a != b')
print test('a <= b')






More information about the Python-list mailing list