python 3's adoption

Duncan Booth duncan.booth at invalid.invalid
Fri Jan 29 08:59:54 EST 2010


Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> wrote:

> If that's too verbose for you, stick this as a helper function in your 
> application:
> 
> 
> def CmpToKey(mycmp):
>     'Convert a cmp= function into a key= function'
>     class K(object):
>         def __init__(self, obj, *args):
>             self.obj = obj
>         __lt__ = lambda s, o: mycmp(s.obj, o.obj) == -1
>         __gt__ = lambda s, o: mycmp(s.obj, o.obj) == 1
>         __eq__ = lambda s, o: mycmp(s.obj, o.obj) == 0
>         __le__ = lambda s, o: mycmp(s.obj, o.obj) != 1
>         __ge__ = lambda s, o: mycmp(s.obj, o.obj) != -1
>         __ne__ = lambda s, o: mycmp(s.obj, o.obj) != 0
>     return K
> 
> 

Shouldn't that be:

def CmpToKey(mycmp):
    'Convert a cmp= function into a key= function'
    class K(object):
        def __init__(self, obj, *args):
            self.obj = obj
        __lt__ = lambda s, o: mycmp(s.obj, o.obj) < 0
        __gt__ = lambda s, o: mycmp(s.obj, o.obj) > 0
        __eq__ = lambda s, o: mycmp(s.obj, o.obj) == 0
        __le__ = lambda s, o: mycmp(s.obj, o.obj) <= 0
        __ge__ = lambda s, o: mycmp(s.obj, o.obj) >= 0
        __ne__ = lambda s, o: mycmp(s.obj, o.obj) != 0
    return K

After all the cmp function needn't return -1,0,1 only negative, 0, 
positive.

And if that's still too verbose for you try:

def CmpToKey(mycmp):
    'Convert a cmp= function into a key= function'
    class K(object):
        def __init__(self, obj, *args):
            self.obj = obj
        __lt__ = lambda s, o: mycmp(s.obj, o.obj) < 0
    return K

That works on 3.1 and 2.6 though of course there's no guarantee that a 
future Python version won't use a different comparison operator so only 
use it if you like living dangerously and have problems typing. :^)


-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list