Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overriding __cmp__ python function

Tags:

python

Hi I am overriding __cmp__ . If the second object passed is None, or if it is not an instance of someClass, then it returns -1.

I don't understand what exactly is happening here.

class someClass():
    def __cmp__(self, obj):
        if obj == None:
            return -1
        if not isinstance(obj, someClass):
            return -1  

My test function:

def test_function(self):  
        obj1 = someClass()
        self.assertTrue(obj1 < None)
        # I get true.
        self.assertTrue(obj1 > None)
        # I get failure as False is returned.

Could anyone please explain to me:

  • What are the return values?
  • How is it deciding whether it will return True or False when the comparison signs are changed?
like image 761
Prashant Kumar Avatar asked Oct 27 '25 10:10

Prashant Kumar


1 Answers

The convention for __cmp__ is:

a < b : return -1
a = b : return 0
a > b : return 1

This of course makes only sense if both a and b are of compatible types, say numbers. If you have a 'corner case', where a or b is either None or incompatible (not instanceof), you should report an error, as this is a programming error in the use of the comparison operators on your someClass instance.

It is possible to implement any behaviour with __cmp__, but a comparison with None the way described by the OP will eventually lead to strange behaviour and bugs.

see also: __lt__ instead of __cmp__ http://docs.python.org/reference/datamodel.html#object.__cmp__

like image 164
Rudolf Mühlbauer Avatar answered Oct 28 '25 22:10

Rudolf Mühlbauer