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

There are no ABCs for ordering operations. This is because the recursive class difinition like:

 class Derived(XXX(Derived)):

is invalid syntax. This recipe implements an ABC ordering class with using decorator.

Python, 46 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
37
38
39
40
41
42
43
44
45
46
import abc

def keycomparable(Derived):
    class KeyComparableImpl(metaclass = abc.ABCMeta):
        @abc.abstractmethod
        def _cmpkey(self):
            pass

        def __lt__(self, other):
            if not isinstance(other, Derived):
                return NotImplemented
            return self._cmpkey() < other._cmpkey()
        
        def __le__(self, other):
            if not isinstance(other, Derived):
                return NotImplemented
            return self._cmpkey() <= other._cmpkey()

        def __eq__(self, other):
            if not isinstance(other, Derived):
                return NotImplemented
            return self._cmpkey() == other._cmpkey()
        
    
    class Wrapper(Derived, KeyComparableImpl):
        pass

    Wrapper.__name__ = Derived.__name__
    Wrapper.__doc__ = Derived.__doc__        
    return Wrapper


@keycomparable
class IntABS:
    "sample class"
    def __init__(self,val):
        self.val = val

    def _cmpkey(self):
        return abs(self.val)

    def __str__(self):
        return str(abs(self.val))

    def __repr__(self):
        return "abs({0})".format(self.val)
Created by Y S on Sat, 16 May 2009 (MIT)
Python recipes (4591)
Y S's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks