custom sorting and __cmp__

L

Lee Harr

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 ...
.... 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
........ pass
....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 :eek:) ?


Is this related in any way to interfaces?
 
E

Emile van Sebille

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

... 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

Instead, how about:
def __cmp__(self,other):
try: return cmp(self.level, other.level)
except return 1 # or -1
 
K

Kristian Ovaska

Lee Harr said:
Should I be catching comparisons to objects that do not have
my 'level' attribute and falling back to id comparison?

I usually solve it like this:

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

def __cmp__(self, other):
if isinstance(other, A):
return cmp(self.level, other.level)
else:
return -1
 
A

Aahz

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 :eek:) ?

Python is these days moving more and more toward preventing
heterogeneous comparisons:
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: can't compare datetime.date to int

However, you should set things up so that you can use ``==``:
False

The easy way to handle this is to use the new special methods for rich
comparisons instead of __cmp__.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top