[Python-3000] Please re-add cmp to python 3000 (original) (raw)
David A. Wheeler dwheeler at dwheeler.com
Mon Oct 29 19:34:03 CET 2007
- Previous message: [Python-3000] Please re-add __cmp__ to python 3000
- Next message: [Python-3000] Please re-add __cmp__ to python 3000
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
I think several postings have explained better than I have on why cmp is still very valuable. (See below.)
Guido van Rossum posted earlier that he was willing to entertain a PEP to restore cmp, so I've attempted to create a draft PEP, posted here: http://www.dwheeler.com/misc/pep-cmp.txt Please let me know if it makes sense. Thanks.
Greg Ewing stated "Why not provide a richcmp method that directly connects with the corresponding type slot? All the comparisons eventually end up there anyway, so it seems like the right place to provide a one-stop comparison method in the 3.0 age." It seems to me that this is the same as "cmp", and if so, let's just keep using the same name (there's nothing wrong with the name!). But maybe I just don't understand the comment, so explanation welcome.
--- David A. Wheeler
========================================
Aahz:
From my perspective, the real use case for cmp() is when you want to do a three-way comparison of a "large" object (for example, a Decimal instance). You can store the result of cmp() and then do a separate three-way branch.
and reply to the note "I'm having troubles coming up with things where the basic operator is really a cmp-like function.", there were two replies..
Guido van Rossum:
Here's one. When implementing the '<' operator on lists or tuples, you really want to call the 'cmp' operator on the individual items, because otherwise (if all you have is == and <) the algorithm becomes something like "compare for equality until you've found the first pair of items that are unequal; then compare those items again using < to decide the final outcome". If you don't believe this, try to implement this operation using only == or < without comparing any two items more than once.
and
Greg Ewing:
Think of things like comparing a tuple. You need to work your way along and recursively compare the elements. The decision about when to stop always involves ==, whatever comparison you're trying to do. So if e.g. you're doing <, then you have to test each element first for <, and if that's false, test it for ==. If the element is itself a tuple, it's doing this on its elements too, etc., and things get very inefficient.
If you have a single cmp operation that you can apply to the elements, you only need to do it once for each element and it gives you all the information you need.
- Previous message: [Python-3000] Please re-add __cmp__ to python 3000
- Next message: [Python-3000] Please re-add __cmp__ to python 3000
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]