Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1# coding=utf-8 

2""" 

3 http://regebro.wordpress.com/2010/12/13/python-implementing-rich-comparison-the-correct-way/ 

4""" 

5 

6__docformat__ = 'restructuredtext en' 

7 

8 

9def _cmp(a, b): 

10 if a < b: 

11 return -1 

12 elif a > b: 

13 return 1 

14 else: 

15 return 0 

16 

17 

18class ComparableMixin(object): 

19 """ 

20 Mix in this class and implement a **_cmpkey()** method to make an object comparable. 

21 """ 

22 def _compare(self, other, method): 

23 """ 

24 Compare an object with this object using the given comparison method. 

25 

26 :param other: object ot compare with 

27 :type other: ComparableMixin 

28 :param method: a comparison method 

29 :type method: lambda 

30 :return: asserted if comparison is true 

31 :rtype: bool 

32 :raises: NotImplemented 

33 """ 

34 try: 

35 return method(self._cmpkey(), other._cmpkey()) 

36 except (AttributeError, TypeError): 

37 # _cmpkey not implemented, or return different type, 

38 # so I can't compare with "other". 

39 return NotImplemented 

40 

41 def _cmpkey(self): 

42 """ 

43 The comparison key must be implemented by the child class and used by the comparison operators. 

44 """ 

45 raise NotImplementedError 

46 

47 def __lt__(self, other): 

48 """ 

49 less than 

50 

51 :param other: the instance to compare to 

52 :type other: ComparableMixin 

53 """ 

54 return self._compare(other, lambda s, o: _cmp(s, o) < 0) 

55 

56 def __le__(self, other): 

57 """ 

58 less than or equal 

59 

60 :param other: the instance to compare to 

61 :type other: ComparableMixin 

62 """ 

63 return self._compare(other, lambda s, o: _cmp(s, o) <= 0) 

64 

65 def __eq__(self, other): 

66 """ 

67 equal 

68 

69 :param other: the instance to compare to 

70 :type other: ComparableMixin 

71 """ 

72 return self._compare(other, lambda s, o: _cmp(s, o) == 0) 

73 

74 def __ge__(self, other): 

75 """ 

76 greater than or equal 

77 

78 :param other: the instance to compare to 

79 :type other: ComparableMixin 

80 """ 

81 return self._compare(other, lambda s, o: _cmp(s, o) >= 0) 

82 

83 def __gt__(self, other): 

84 """ 

85 greater than 

86 

87 :param other: the instance to compare to 

88 :type other: ComparableMixin 

89 """ 

90 return self._compare(other, lambda s, o: _cmp(s, o) > 0) 

91 

92 def __ne__(self, other): 

93 """ 

94 not equal 

95 

96 :param other: the instance to compare to 

97 :type other: ComparableMixin 

98 """ 

99 return self._compare(other, lambda s, o: _cmp(s, o) != 0)