[PATCH] sort with key and reverse keywors in Python2.4

Mario Pernici Mario.Pernici at mi.infn.it
Thu Jun 2 15:03:13 BST 2005


On Thu, 2 Jun 2005, Aaron Bentley wrote:
> Is there a compelling reason to use Python 2.4's sort facilities?  I
> recognize that they're nicer, but in general, I think it's better to
> have one codepath, instead of two.  The code's cleaner that way, and
> it's easier to test.
> 
> Of course, there are always exceptions if there's a good enough reason.

In a simple case such as
def key1(x):
  return x%10

a = range(1000)
my_sort(a, key1)

Python2.4 is about 9 times faster than Python2.3 on my machine.
It is an optimization at no cost; the proposed patch
works with both Python versions, so it gives no problems
in testing.

On Thu, 2 Jun 2005, Andrew Bennetts wrote:
> It's also the sort of thing that deserves a comment justifying it and
> explaining it. "# Try to use Python 2.4's faster sorting, otherwise 
fallback
> to 2.3's." would make a huge difference to readability, and make it 
easier
> to spot and clean up this cruft when python 2.4 is considered ubiquitous
> enough to drop 2.3 support in bzr.

I added the suggested comment in the patch.

Mario
-------------- next part --------------
--- changeset.py	2005-05-26 04:11:57.000000000 +0200
+++ changeset1.py	2005-06-02 15:43:55.359809812 +0200
@@ -781,13 +781,19 @@
     :param reverse: If true, sort in reverse order
     :type reverse: bool
     """
-    def cmp_by_key(entry_a, entry_b):
+    # Try to use Python 2.4's faster sorting, otherwise fallback
+    # to Python 2.3
+    try:
+        sequence.sort(key=key, reverse=reverse)
+    except TypeError:
         if reverse:
-            tmp=entry_a
-            entry_a = entry_b
-            entry_b = tmp
-        return cmp(key(entry_a), key(entry_b))
-    sequence.sort(cmp_by_key)
+            def cmp_by_key(entry_a, entry_b):
+                return cmp(key(entry_b), key(entry_a))
+        else:
+            def cmp_by_key(entry_a, entry_b):
+                return cmp(key(entry_a), key(entry_b))
+        sequence.sort(cmp_by_key)
+
 
 def get_rename_entries(changeset, inventory, reverse):
     """Return a list of entries that will be renamed.  Entries are sorted from


More information about the bazaar mailing list