]> granicus.if.org Git - python/commitdiff
Convert some custom sort comparison functions to equivalent key functions.
authorRaymond Hettinger <python@rcn.com>
Wed, 30 Jan 2008 02:55:10 +0000 (02:55 +0000)
committerRaymond Hettinger <python@rcn.com>
Wed, 30 Jan 2008 02:55:10 +0000 (02:55 +0000)
12 files changed:
Lib/bsddb/dbtables.py
Lib/bsddb/test/test_compare.py
Lib/ctypes/util.py
Lib/idlelib/MultiCall.py
Lib/idlelib/TreeWidget.py
Lib/pyclbr.py
Lib/pydoc.py
Lib/tarfile.py
Lib/unittest.py
Tools/pynche/ColorDB.py
Tools/scripts/finddiv.py
Tools/unicode/makeunicodedata.py

index 56b4e3a01d15cdaafd7f3876030ad30bd406c8f2..563390ba6fcce8489be10e7c5923adb8434e51d5 100644 (file)
@@ -88,6 +88,15 @@ class LikeCond(Cond):
     def __call__(self, s):
         return self.re.match(s.decode(self.encoding))
 
+def CmpToKey(mycmp):
+    'Convert a cmp= function into a key= function'
+    class K(object):
+        def __init__(self, obj, *args):
+            self.obj = obj
+        def __lt__(self, other):
+            return mycmp(self.obj, other.obj) == -1
+    return K
+
 #
 # keys used to store database metadata
 #
@@ -587,7 +596,7 @@ class bsdTableDB :
             return 0
 
         conditionlist = list(conditions.items())
-        conditionlist.sort(cmp_conditions)
+        conditionlist.sort(key=CmpToKey(cmp_conditions))
 
         # Apply conditions to column data to find what we want
         cur = self.db.cursor()
index a36faae3600ecb40679d728034889610a360bd75..49aa7caba0341dc7f156149cacb0e9a1df03af35 100644 (file)
@@ -32,10 +32,20 @@ _expected_lexical_test_data = [s.encode('ascii') for s in
 _expected_lowercase_test_data = [s.encode('ascii') for s in
         ('', 'a', 'aaa', 'b', 'c', 'CC', 'cccce', 'ccccf', 'CCCP')]
 
+
+def CmpToKey(mycmp):
+    'Convert a cmp= function into a key= function'
+    class K(object):
+        def __init__(self, obj, *args):
+            self.obj = obj
+        def __lt__(self, other):
+            return mycmp(self.obj, other.obj) == -1
+    return K
+
 class ComparatorTests (unittest.TestCase):
     def comparator_test_helper (self, comparator, expected_data):
         data = expected_data[:]
-        data.sort (comparator)
+        data.sort (key=CmpToKey(comparator))
         self.failUnless (data == expected_data,
                          "comparator `%s' is not right: %s vs. %s"
                          % (comparator, expected_data, data))
index 733a99c4d7a2ab4cc774431a7781755abc5ca3a4..3e6ae0104bfe3be03abbc3b92171490b20b23494 100644 (file)
@@ -123,7 +123,7 @@ elif os.name == "posix":
             res = re.findall(expr, data)
             if not res:
                 return _get_soname(_findLib_gcc(name))
-            res.sort(cmp= lambda x,y: cmp(_num_version(x), _num_version(y)))
+            res.sort(key=_num_version)
             return res[-1]
 
     else:
index 9e9e40c19fb4c862632d1f56ed2d1f31d85aa0dd..c59ccfe57ac6bfabcd0d7145bca37a831a7e1e7a 100644 (file)
@@ -125,7 +125,7 @@ def expand_substates(states):
     statelist = []
     for state in states:
         substates = list(set(state & x for x in states))
-        substates.sort(lambda a,b: nbits(b) - nbits(a))
+        substates.sort(key=nbits, reverse=True)
         statelist.append(substates)
     return statelist
 
index c5084101baf34f2d39172b43e8eb33b84311c917..0009de87638e39bedfa14ed41891084b7c69ecbf 100644 (file)
@@ -398,7 +398,7 @@ class FileTreeItem(TreeItem):
             names = os.listdir(self.path)
         except os.error:
             return []
-        names.sort(lambda a, b: cmp(os.path.normcase(a), os.path.normcase(b)))
+        names.sort(key = os.path.normcase)
         sublist = []
         for name in names:
             item = FileTreeItem(os.path.join(self.path, name))
index c402a0994a8b1f912cc702e9a56db57a7c0ae7bb..cf4951c6d718ff1c1983966c59342886bb4a8875 100644 (file)
@@ -324,8 +324,7 @@ def _main():
         path = []
     dict = readmodule_ex(mod, path)
     objs = dict.values()
-    objs.sort(lambda a, b: cmp(getattr(a, 'lineno', 0),
-                               getattr(b, 'lineno', 0)))
+    objs.sort(key=lambda a: getattr(a, 'lineno', 0))
     for obj in objs:
         if isinstance(obj, Class):
             print("class", obj.name, obj.super, obj.lineno)
index 0fdbb900a82a62e1534293b69c5411298aa4a356..de8d193f50f14c6ac517681342da59abbe25f7c6 100755 (executable)
@@ -797,10 +797,7 @@ class HTMLDoc(Doc):
             tag += ':<br>\n'
 
             # Sort attrs by name.
-            try:
-                attrs.sort(key=lambda t: t[0])
-            except TypeError:
-                attrs.sort(lambda t1, t2: cmp(t1[0], t2[0]))    # 2.3 compat
+            attrs.sort(key=lambda t: t[0])
 
             # Pump out the attrs, segregated by kind.
             attrs = spill('Methods %s' % tag, attrs,
index 9ea92d0ebde91afcb06071173b353edd9c0d9427..b184ed83b7904ce7c01d8c534b719894da01053b 100644 (file)
@@ -2016,7 +2016,7 @@ class TarFile(object):
                 self.extract(tarinfo, path)
 
         # Reverse sort directories.
-        directories.sort(lambda a, b: cmp(a.name, b.name))
+        directories.sort(key=lambda a: a.name)
         directories.reverse()
 
         # Set correct owner, mtime and filemode on directories.
index adbbe8a0945f4a5193319d471ccf5e63ac10b7f7..742871bd2337e30885f6a3ec6de73fbc48c76ee4 100644 (file)
@@ -504,6 +504,15 @@ class FunctionTestCase(TestCase):
 # Locating and loading tests
 ##############################################################################
 
+def CmpToKey(mycmp):
+    'Convert a cmp= function into a key= function'
+    class K(object):
+        def __init__(self, obj, *args):
+            self.obj = obj
+        def __lt__(self, other):
+            return mycmp(self.obj, other.obj) == -1
+    return K
+
 class TestLoader:
     """This class is responsible for loading tests according to various
     criteria and returning them wrapped in a TestSuite
@@ -598,7 +607,7 @@ class TestLoader:
                    and hasattr(getattr(testCaseClass, attrname), '__call__')
         testFnNames = list(filter(isTestMethod, dir(testCaseClass)))
         if self.sortTestMethodsUsing:
-            testFnNames.sort(self.sortTestMethodsUsing)
+            testFnNames.sort(key=CmpToKey(self.sortTestMethodsUsing))
         return testFnNames
 
 
index 3b978fb74a7d66f165e77f2b065f0653a40c40c6..6d52b40e2ee9435f2d2149087a3537ed2d3c4431 100644 (file)
@@ -122,10 +122,7 @@ class ColorDB:
             self.__allnames = []
             for name, aliases in self.__byrgb.values():
                 self.__allnames.append(name)
-            # sort irregardless of case
-            def nocase_cmp(n1, n2):
-                return cmp(n1.lower(), n2.lower())
-            self.__allnames.sort(nocase_cmp)
+            self.__allnames.sort(key=unicode.lower)
         return self.__allnames
 
     def aliases_of(self, red, green, blue):
index 9d5862bb915911148de9eee4c53fcf8a147db2ae..558791fcc0afe69b046fae4fb8a878a14106d07b 100755 (executable)
@@ -78,7 +78,7 @@ def processdir(dir, listnames):
         fn = os.path.join(dir, name)
         if os.path.normcase(fn).endswith(".py") or os.path.isdir(fn):
             files.append(fn)
-    files.sort(lambda a, b: cmp(os.path.normcase(a), os.path.normcase(b)))
+    files.sort(key=os.path.normcase)
     exit = None
     for fn in files:
         x = process(fn, listnames)
index 5b5b5dc7c1ed753c250078378255b355e9dbae08..f080ca2da3373a376a6cb0eebf580c6034bb3373 100644 (file)
@@ -441,6 +441,15 @@ def makeunicodetype(unicode, trace):
 # --------------------------------------------------------------------
 # unicode name database
 
+def CmpToKey(mycmp):
+    'Convert a cmp= function into a key= function'
+    class K(object):
+        def __init__(self, obj, *args):
+            self.obj = obj
+        def __lt__(self, other):
+            return mycmp(self.obj, other.obj) == -1
+    return K
+
 def makeunicodename(unicode, trace):
 
     FILE = "Modules/unicodename_db.h"
@@ -490,7 +499,7 @@ def makeunicodename(unicode, trace):
         if r:
             return r
         return cmp(aword, bword)
-    wordlist.sort(cmpwords)
+    wordlist.sort(key=CmpToKey(cmpwords))
 
     # figure out how many phrasebook escapes we need
     escapes = 0
@@ -514,7 +523,7 @@ def makeunicodename(unicode, trace):
     # length (to maximize overlap)
 
     wordlist, wordtail = wordlist[:short], wordlist[short:]
-    wordtail.sort(lambda a, b: len(b[0])-len(a[0]))
+    wordtail.sort(key=lambda a: a[0], reverse=True)
     wordlist.extend(wordtail)
 
     # generate lexicon from words