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 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.

Reply

The content of this field is kept private and will not be shown publicly.
  • Lines and paragraphs break automatically.
  • You may use [acidfree:xx] tags to display acidfree videos or images inline.

More information about formatting options

Back to top