custom sorting and __cmp__

Aahz aahz at
Wed Dec 3 03:10:19 CET 2003

In article <slrnbsk5ms.1pe.missive at>,
Lee Harr  <missive at> wrote:
>>>> 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) ?

Python is these days moving more and more toward preventing
heterogeneous comparisons:

>>> import datetime, time
>>> d>1
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: can't compare to int

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

>>> d==1

The easy way to handle this is to use the new special methods for rich
comparisons instead of __cmp__.
Aahz (aahz at           <*>

Weinberg's Second Law: If builders built buildings the way programmers wrote 
programs, then the first woodpecker that came along would destroy civilization.

More information about the Python-list mailing list