So, rather than using == to compare identities in your code, use "is" as Tim suggests (Thanks Tim). This allows you to strip the id() checks from the __cmp__ operator and let it be used strictly for value comparisons. It is probably a good idea to allow for comparison against None (Null pointer sort of thing) but to raise a proper exception when comparing against something other than an Swartz or a descendent of that class hierarchy.
def __cmp__(mine, yours):
if yours is None:
return 1
if not isinstance(yours, Swartz):
raise TypeError
if mine.val < yours.val:
return -1
if mine.val > yours.val:
return 1
return 0
There are additional "rich comparison" operators that provide for more flexibility than __cmp__() and one should consider the implications associated with __hash__() when implementing custom comparators. See the Python Data Model Documentation on this.
A better __cmp__()
So, rather than using == to compare identities in your code, use "is" as Tim suggests (Thanks Tim). This allows you to strip the id() checks from the __cmp__ operator and let it be used strictly for value comparisons. It is probably a good idea to allow for comparison against None (Null pointer sort of thing) but to raise a proper exception when comparing against something other than an Swartz or a descendent of that class hierarchy.
def __cmp__(mine, yours): if yours is None: return 1 if not isinstance(yours, Swartz): raise TypeError if mine.val < yours.val: return -1 if mine.val > yours.val: return 1 return 0There are additional "rich comparison" operators that provide for more flexibility than __cmp__() and one should consider the implications associated with __hash__() when implementing custom comparators. See the Python Data Model Documentation on this.