views:

135

answers:

2

First the code:

class myClass(object):
    def __cmp__(self, other):
        return cmp(type(self), type(other)) or cmp(self.__something, other.__something)

Does this produce the same ordering as for other types in python? Is there a correct idiom for this?

Related question:

A bit of looking around on google I found some pertinent information in the python docs. Quoting:

Implementation note: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.

This suggests that If I want to follow that behavior, I should use

class myClass(object):
    def __cmp__(self, other):
        return (cmp(self.__class__.__name__, other.__class__.__name) or 
                cmp(self.__something, other.__something))

Especially unfortunate is that I may have an extraordinarily difficult time mantaining transitivity with dicts, which is a special case I had hoped to implement.

Do I even need to check the types of my arguments? does python even let me see this?

+1  A: 

Python 2 unfortunately did support such "alien" comparisons (fortunately abrogated in Python 3). It's NOT easy to emulate the built-ins behavior because it has so many special cases, for example float and int compare directly (no type-comparison override as you have it coded) but complex makes any comparison (except == and !=) always raise an exception. Do you really need to emulate all of these quirks and wiggles? Such a need would be very unusual. If your type is "numeric" (e.g. look at decimal.Decimal) it needs to play nice with other numerical types, I guess, but types that aren't "comparable numbers" have fewer real-word sensible constraints...!

Alex Martelli
A: 

What are you actually trying to do? Why would you want to sort or compare instances of different classes by class/type?

It's hard to propose a solution when you haven't actually posted the problem.

You need to define your own comparison methods for custom classes, and it's largely up to you to make sure any comparisons you perform make sense.

Please explain what you are trying to achieve. This might not be the Pythonic way.

wbg