custom sorting and __cmp__

From: Lee Harr (missive_at_frontiernet.net)
Date: 11/30/03


Date: Sun, 30 Nov 2003 16:13:15 GMT


Let's say I have a class

class A:
    def __init__(self, level):
        self.level = level

and I want to put some of these in a list and sort the list
by level

a1 = A(1)
a2 = A(2)
l = [a1, a2]
l.sort()

Am I better off creating a __cmp__ method for my class or
making a cmp function to pass to sort?

My thought was that __cmp__ would be perfect, but then I
started thinking about this ...

>>> class A:
... def __init__(self, level):
... self.level = level
... def __cmp__(self, other):
... if self.level > other.level:
... return 1
... elif self.level < other.level:
... return -1
... else:
... return 0
...
>>> a1 = A(1)
>>> a2 = A(2)
>>> class C:
... pass
...
>>> c = C()
>>> a1 == a2
False
>>> a1 < a2
True
>>> a1 == c
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 5, in __cmp__
AttributeError: C instance has no attribute 'level'

Should I be catching comparisons to objects that do not have
my 'level' attribute and falling back to id comparison?
Or am I worried about nothing (YAGNI :o) ?

Is this related in any way to interfaces?



Relevant Pages

  • Re: how to vary sorts block?
    ... I want to be able to sort that array by ... def initialize ... Thing = Struct.new(:name,:amount) ...
    (comp.lang.ruby)
  • Re: BASIC - removing and replacing string characters
    ... Folderol wrote: ... DEF FNfoo ... This sort of thing is much easier being dumped into a byte ... array and then manipulated with indirection operators. ...
    (comp.sys.acorn.programmer)
  • sorting tasks by importance and urgency
    ... algorithmically sort a set of business tasks which have an associated ... To sort by importance: I just consider the proportional value of each ... rnd(self.priority), rnd, rnd ... def priority: ...
    (comp.lang.python)
  • Re: manually sort array of numbers
    ... def max_array_index ... Also, the built in sort is implemented in C, so it is much quicker. ... Here is a benchmark showing that in an array of 5000 integers, ...
    (comp.lang.ruby)
  • Re: [SORT?] by x,y allowing x,y to be passed as parms
    ... and a couple of methods to sort array of pointers by any two fields. ... def initialize @list_of_CDs = Array.new end ...
    (comp.lang.ruby)