What is the preferred way to sort/compare custom objects?
Jeremy
jlconlin at gmail.com
Thu Feb 24 12:52:40 EST 2011
On Thursday, February 24, 2011 10:09:53 AM UTC-7, Chris Rebert wrote:
> On Thu, Feb 24, 2011 at 8:27 AM, Jeremy <jlco... 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.
I implemented __eq__ and __lt__ (and used functoos, thanks for the suggestion) and sorting works. Thanks for the help. Most importantly, I wanted to make sure I was doing this the right way and your post helped.
Jeremy
More information about the Python-list
mailing list