4

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?
DJMcMayhem
  • 7,285
  • 4
  • 41
  • 61
Prashant Kumar
  • 308
  • 2
  • 3
  • 19

3 Answers3

8

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__

Community
  • 1
  • 1
Rudolf Mühlbauer
  • 2,511
  • 16
  • 18
  • 1
    And any two objects should compare the opposite if they are passed in the other way around. Otherwise some assumptions that Python makes about orders are not valid. – Will Oct 16 '12 at 07:01
3

When the obj is None, your program will return -1, while returning a negative integer means self < obj, so obj1 < None is True, and obj1 > None is false.

Marcus
  • 6,701
  • 4
  • 19
  • 28
  • I din't understand how you have made the conclusion that obj1 > None is false. – Prashant Kumar Oct 16 '12 at 07:08
  • @PrashantKumar, actually the python don't care what the operator is, it just calculate `cmp(obj1,None)` and see what value will be returned, in your case, the value is -1, so the interpreter tells that `obj1 > None` is false. – Marcus Oct 16 '12 at 07:12
1

If you look at the python documentation, you'll see that the cmp function return -1 if self < other.

Since __cmp__(obj, None) == -1, it assumed that obj < None.

My guess if __cmp__(obj, None) should return 1 as any object is superior to no object :)

Samy Arous
  • 6,794
  • 13
  • 20
  • sorry it din't help. My question is from what we made the conclusion that (obj1 < None) will get True and (obj1 > None) will get False. – Prashant Kumar Oct 16 '12 at 07:04