What is the preferred way to sort/compare custom objects?

Chris Rebert clp2 at rebertia.com
Thu Feb 24 12:09:53 EST 2011


On Thu, Feb 24, 2011 at 8:27 AM, Jeremy <jlconlin at gmail.com> wrote:
> I just discovered the wiki page on sorting (http://wiki.python.org/moin/HowTo/Sorting/).  This describes the new way of sorting a container instead of using the cmp function.  But what do I do for custom objects?
> If I write __lt__, __gt__, etc. functions for my objects, will these be used?

s/functions/methods/
Yes, they will. As Bill Nye would say: "Try It!". The REPL exists for a reason.

If you're using Python 2.7+, you may want to use
functools.total_ordering()
[http://docs.python.org/library/functools.html#functools.total_ordering
] for convenience.

> Is this better than defining a key for sorting my custom objects?

Unless there are multiple "obvious" ways to sort your objects, yes.
Third-party code will be able to sort+compare your objects. Sorting
your objects in your own code will be more concise. And you'll be able
to use the comparison operators on your objects.

Note that, internally, it may be convenient to define the comparison
methods in terms of a key comparison. For example:

class Person(object):
    def __init__(self, first, last):
        self.first_name = first
        self.last_name = last
    def _key(self):
        return (self.last_name, self.first_name)
    def __lt__(self, other):
        return self._key() < other._key()
    # continue defining other comparison methods analogously...

Cheers,
Chris



More information about the Python-list mailing list