ActiveState Code

Recipe 576526: compare(), making filter() fun again


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
Python
 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)

Comments

  1. 1. At 10:40 a.m. on 26 oct 2008, Eric Rose said:

    Lambda?

    for i in filter(lambda x: double(x) > 5, items):
        print i #Prints 3, 4 and 5
    

Sign in to comment