Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 266981
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T23:29:17+00:00 2026-05-11T23:29:17+00:00

Python 2.x has two ways to overload comparison operators, __cmp__ or the rich comparison

  • 0

Python 2.x has two ways to overload comparison operators, __cmp__ or the “rich comparison operators” such as __lt__. The rich comparison overloads are said to be preferred, but why is this so?

Rich comparison operators are simpler to implement each, but you must implement several of them with nearly identical logic. However, if you can use the builtin cmp and tuple ordering, then __cmp__ gets quite simple and fulfills all the comparisons:

class A(object):
  def __init__(self, name, age, other):
    self.name = name
    self.age = age
    self.other = other
  def __cmp__(self, other):
    assert isinstance(other, A) # assumption for this example
    return cmp((self.name, self.age, self.other),
               (other.name, other.age, other.other))

This simplicity seems to meet my needs much better than overloading all 6(!) of the rich comparisons. (However, you can get it down to “just” 4 if you rely on the “swapped argument”/reflected behavior, but that results in a net increase of complication, in my humble opinion.)

Are there any unforeseen pitfalls I need to be made aware of if I only overload __cmp__?

I understand the <, <=, ==, etc. operators can be overloaded for other purposes, and can return any object they like. I am not asking about the merits of that approach, but only about differences when using these operators for comparisons in the same sense that they mean for numbers.

Update: As Christopher pointed out, cmp is disappearing in 3.x. Are there any alternatives that make implementing comparisons as easy as the above __cmp__?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-11T23:29:17+00:00Added an answer on May 11, 2026 at 11:29 pm

    Yep, it’s easy to implement everything in terms of e.g. __lt__ with a mixin class (or a metaclass, or a class decorator if your taste runs that way).

    For example:

    class ComparableMixin:
      def __eq__(self, other):
        return not self<other and not other<self
      def __ne__(self, other):
        return self<other or other<self
      def __gt__(self, other):
        return other<self
      def __ge__(self, other):
        return not self<other
      def __le__(self, other):
        return not other<self
    

    Now your class can define just __lt__ and multiply inherit from ComparableMixin (after whatever other bases it needs, if any). A class decorator would be quite similar, just inserting similar functions as attributes of the new class it’s decorating (the result might be microscopically faster at runtime, at equally minute cost in terms of memory).

    Of course, if your class has some particularly fast way to implement (e.g.) __eq__ and __ne__, it should define them directly so the mixin’s versions are not use (for example, that is the case for dict) — in fact __ne__ might well be defined to facilitate that as:

    def __ne__(self, other):
      return not self == other
    

    but in the code above I wanted to keep the pleasing symmetry of only using <;-).
    As to why __cmp__ had to go, since we did have __lt__ and friends, why keep another, different way to do exactly the same thing around? It’s just so much dead-weight in every Python runtime (Classic, Jython, IronPython, PyPy, …). The code that definitely won’t have bugs is the code that isn’t there — whence Python’s principle that there ought to be ideally one obvious way to perform a task (C has the same principle in the “Spirit of C” section of the ISO standard, btw).

    This doesn’t mean we go out of our way to prohibit things (e.g., near-equivalence between mixins and class decorators for some uses), but it definitely does mean that we don’t like to carry around code in the compilers and/or runtimes that redundantly exists just to support multiple equivalent approaches to perform exactly the same task.

    Further edit: there’s actually an even better way to provide comparison AND hashing for many classes, including that in the question — a __key__ method, as I mentioned on my comment to the question. Since I never got around to writing the PEP for it, you must currently implement it with a Mixin (&c) if you like it:

    class KeyedMixin:
      def __lt__(self, other):
        return self.__key__() < other.__key__()
      # and so on for other comparators, as above, plus:
      def __hash__(self):
        return hash(self.__key__())
    

    It’s a very common case for an instance’s comparisons with other instances to boil down to comparing a tuple for each with a few fields — and then, hashing should be implemented on exactly the same basis. The __key__ special method addresses that need directly.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 185k
  • Answers 185k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer In my experience, when a buildCommand fails because it is… May 12, 2026 at 4:57 pm
  • Editorial Team
    Editorial Team added an answer These are the characters which are very often confused. For… May 12, 2026 at 4:57 pm
  • Editorial Team
    Editorial Team added an answer Note that Check boxes and Radio buttons are Buttons. So… May 12, 2026 at 4:57 pm

Related Questions

Building on How Do You Express Binary Literals in Python , I was thinking
I'm running Python 2.5, so this question may not apply to Python 3. When
I'm wondering if Python has anything like the C# anonymous classes feature. To clarify,
I wonder if anyone has any recommendations as to setup of emacs 23 on

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.