mirror of
https://github.com/python/cpython.git
synced 2026-01-04 14:32:21 +00:00
Remove duplicates of cmp_to_key (#12542, reviewed by Raymond Hettinger)
This commit is contained in:
parent
45dedaafc2
commit
41bade96a4
2 changed files with 13 additions and 26 deletions
|
|
@ -4,17 +4,10 @@
|
|||
|
||||
import sys
|
||||
import os
|
||||
from functools import cmp_to_key
|
||||
|
||||
from test import support, seq_tests
|
||||
|
||||
def CmpToKey(mycmp):
|
||||
'Convert a cmp= function into a key= function'
|
||||
class K(object):
|
||||
def __init__(self, obj):
|
||||
self.obj = obj
|
||||
def __lt__(self, other):
|
||||
return mycmp(self.obj, other.obj) == -1
|
||||
return K
|
||||
|
||||
class CommonTest(seq_tests.CommonTest):
|
||||
|
||||
|
|
@ -443,7 +436,7 @@ def revcmp(a, b):
|
|||
return 1
|
||||
else: # a > b
|
||||
return -1
|
||||
u.sort(key=CmpToKey(revcmp))
|
||||
u.sort(key=cmp_to_key(revcmp))
|
||||
self.assertEqual(u, self.type2test([2,1,0,-1,-2]))
|
||||
|
||||
# The following dumps core in unpatched Python 1.5:
|
||||
|
|
@ -456,7 +449,7 @@ def myComparison(x,y):
|
|||
else: # xmod > ymod
|
||||
return 1
|
||||
z = self.type2test(range(12))
|
||||
z.sort(key=CmpToKey(myComparison))
|
||||
z.sort(key=cmp_to_key(myComparison))
|
||||
|
||||
self.assertRaises(TypeError, z.sort, 2)
|
||||
|
||||
|
|
@ -468,7 +461,8 @@ def selfmodifyingComparison(x,y):
|
|||
return -1
|
||||
else: # x > y
|
||||
return 1
|
||||
self.assertRaises(ValueError, z.sort, key=CmpToKey(selfmodifyingComparison))
|
||||
self.assertRaises(ValueError, z.sort,
|
||||
key=cmp_to_key(selfmodifyingComparison))
|
||||
|
||||
self.assertRaises(TypeError, z.sort, 42, 42, 42, 42)
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue