summaryrefslogtreecommitdiffstats
path: root/pym
diff options
context:
space:
mode:
authorZac Medico <zmedico@gentoo.org>2009-03-11 03:35:29 +0000
committerZac Medico <zmedico@gentoo.org>2009-03-11 03:35:29 +0000
commit388fdc5e852349758b81115dfd79e1f852cf19be (patch)
tree7e202bcef8ff253d01ef2d5c9cf6f62d22d00702 /pym
parentf782e318cfc10b8826f5668f5bab23b3e8f39da7 (diff)
downloadportage-388fdc5e852349758b81115dfd79e1f852cf19be.tar.gz
portage-388fdc5e852349758b81115dfd79e1f852cf19be.tar.bz2
portage-388fdc5e852349758b81115dfd79e1f852cf19be.zip
Add a cmp_sort_key class which makes it easier to port code for python-3.0
compatibility. It works by generating key objects which use the given cmp function to implement their __lt__ method. (trunk r12571) svn path=/main/branches/2.1.6/; revision=12852
Diffstat (limited to 'pym')
-rw-r--r--pym/portage/util.py36
1 files changed, 36 insertions, 0 deletions
diff --git a/pym/portage/util.py b/pym/portage/util.py
index ab7214070..def0d3e40 100644
--- a/pym/portage/util.py
+++ b/pym/portage/util.py
@@ -605,6 +605,42 @@ def dump_traceback(msg, noiselevel=1):
writemsg(error+"\n", noiselevel=noiselevel)
writemsg("====================================\n\n", noiselevel=noiselevel)
+class cmp_sort_key(object):
+ """
+ In python-3.0 the list.sort() method no longer has a "cmp" keyword
+ argument. This class acts as an adapter which converts a cmp function
+ into one that's suitable for use as the "key" keyword argument to
+ list.sort(), making it easier to port code for python-3.0 compatibility.
+ It works by generating key objects which use the given cmp function to
+ implement their __lt__ method.
+ """
+ __slots__ = ("_cmp_func",)
+
+ def __init__(self, cmp_func):
+ """
+ @type cmp_func: callable which takes 2 positional arguments
+ @param cmp_func: A cmp function.
+ """
+ self._cmp_func = cmp_func
+
+ def __call__(self, lhs):
+ return self._cmp_key(self._cmp_func, lhs)
+
+ class _cmp_key(object):
+ __slots__ = ("_cmp_func", "_obj")
+
+ def __init__(self, cmp_func, obj):
+ self._cmp_func = cmp_func
+ self._obj = obj
+
+ def __lt__(self, other):
+ if not isinstance(other, self.__class__):
+ raise TypeError("Expected type %s, got %s" % \
+ (self.__class__, other.__class__))
+ if self._cmp_func(self._obj, other._obj) < 0:
+ return True
+ return False
+
def unique_array(s):
"""lifted from python cookbook, credit: Tim Peters
Return a list of the elements in s in arbitrary order, sans duplicates"""