Welcome, guest | Sign In | My Account | Store | Cart

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, 36 lines
 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)

1 comment

Eric Rose 13 years, 1 month ago  # | flag

Lambda?

for i in filter(lambda x: double(x) > 5, items):
    print i #Prints 3, 4 and 5
Created by Andreas Nilsson on Sat, 4 Oct 2008 (MIT)
Python recipes (4591)
Andreas Nilsson's recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks