Comparing heterogeneous types in python

First code:

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

Does this mean the same order as for other types in python? Is there a proper idiom for this?

Related Question:

Looking back a bit on google, I found some relevant information in python docs . Citation:

Implementation Note:. Objects of various types, with the exception of numbers, are ordered by their type names; objects of the same types that do not support the correct comparison are ordered by their address.

This suggests that if I want to follow this 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)) 

It is especially sad that I can have an extremely difficult time preserving transitivity with dict s, which is a special case that I was hoping to implement.

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

+4
source share
2 answers

Python 2, unfortunately, supported such "alien" comparisons (fortunately, it was canceled in Python 3). It is not easy to emulate the behavior of inline elements, because it has so many special cases, for example, float and int are compared directly (without overriding the type of comparison, as you encoded it), but the complex does any comparison (except == and! =) Always raise an exception . Do you really need to imitate all these quirks and movements? Such a need would be very unusual. If your type is "numeric" (for example, look at decimal.Decimal), it seems to play well with other numerical types, but types that are not "comparable numbers" have fewer real reasonable restrictions ...!

+1
source

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

It is difficult to propose a solution if you have not actually posted the problem.

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

Please explain what you are trying to achieve. This may not be the pythonic path.

0
source

All Articles