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

J

Jeremy

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 ofusing 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? Is thisbetter than defining a key for sorting my custom objects?

Thanks,
Jeremy
 
C

Chris Rebert

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 thesebe 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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,240
Members
46,830
Latest member
HeleneMull

Latest Threads

Top