Dynamic comparison operators
Alain Ketterlin
alain at dpt-info.u-strasbg.fr
Thu May 24 10:37:03 EDT 2012
mlangenhoven at gmail.com writes:
> I would like to pass something like this into a function
> test(val1,val2,'>=')
>
> and it should come back with True or False.
def test(x,y,c):
return c(x,y)
Call with: test(v1,v2, lambda x,y:x<=y ). A bit noisy imho.
If you have a finite number of comparison operators, put them in a dict:
compares = dict([ ("<",lambda x,y:x<y),
("|<",lambda x,y: x.startswith(y)),
... ])
and use them like: test(v1,v2,compares["<="]), or simply:
compares["<="](v1,v2)
-- Alain.
More information about the Python-list
mailing list