compare() takes a function parameter and returns a callable comparator when compared to a value. When called, the comparator returns result of comparing the result of calling the function and the value it was created with.
Basic usage:
items = [1, 2, 3, 4, 5]
def double(x):
return x * 2
for i in filter(compare(double) > 5, items):
print i #Prints 3, 4 and 5
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | class compare(object):
def __init__(self, function):
self.function = function
def __eq__(self, other):
def c(l, r): return l == r
return comparator(self.function, c, other)
def __ne__(self, other):
def c(l, r): return l != r
return comparator(self.function, c, other)
def __lt__(self, other):
def c(l, r): return l < r
return comparator(self.function, c, other)
def __le__(self, other):
def c(l, r): return l <= r
return comparator(self.function, c, other)
def __gt__(self, other):
def c(l, r): return l > r
return comparator(self.function, c, other)
def __ge__(self, other):
def c(l, r): return l >= r
return comparator(self.function, c, other)
class comparator(object):
def __init__(self, function, comparison, value):
self.function = function
self.comparison = comparison
self.value = value
def __call__(self, *arguments, **keywords):
return self.comparison(self.function(*arguments, **keywords), self.value)
|
Lambda?