Question about sorted in Python 3.0rc1

josh logan dear.jay.logan at gmail.com
Mon Sep 22 05:05:06 CEST 2008


Hello,


I have 2 questions. Say I have this class:

class Player(object):
    def __init__(self, fname, lname, score):
        self.score = score
        self.fname = fname
        self.lname = lname
    def __cmp__(self, other):
        return (-cmp(self.score, other.score) or
                cmp(self.lname, other.lname) or
                cmp(self.fname, other.fname))
    def __repr__(self):
        return 'Player(fname={0.fname}, lname={0.lname},
score={0.score})'.format(self)
    def __eq__(self, others):
        if isinstance(other, Player):
            return (self.score == other.score and
                    self.lname == other.lname and
                    self.fname == other.fname)
        return False
    def __ne__(self, others):
        return not self.__eq__(others)



fnames = ['Julie', 'Ben', 'Jason', 'David']
lnames = ['Parks', 'Smith']
scores = [100, 95, 95, 130, 58, 74]

import itertools as it

score_iter = it.cycle(scores)

P = [Player(fn, ln, next(score_iter)) for fn in fnames for ln in
lnames]

cmp(P[0], P[1]) # returns -1

sorted(P) # throws TypeError: unorderable types Player() < Player()

The sorted function works when I define __lt__.
I must be misreading the documentation, because I read for the
documentation __cmp__ that it is called if none of the other rich
comparison functions are defined.
Is this a bug in Python 3.0rc1, or am I missing something?


Secondly, say that we suddenly need another sorting order, where we
want to sort by decreasing score and then by DECREASING last name
(instead of increasing last name, defined above). Now that the
comparison function argument is taken away from the sorted builtin,
how do we accomplish this with the "key" parameter?

Thank you




More information about the Python-list mailing list