Python has what is probably the most elegant way of sorting a collection of objects by their attribute values:
|
|
Let’s break it down.
sorted()
We start with the sorted()
function.
It returns a new sorted list from the items in its first argument.
|
|
sorted()
also takes an optional key
function.
key
, when provided, is used to extract a comparison key from the items being sorted.
|
|
This also means that if we want to sort custom objects by a given attribute, we can write:
|
|
|
|
Which is great, but what if we want to sort by age and by name?
tuple
Tuples are usually immutable sequences of heterogeneous elements.
Python’s tuple
has the added property of being compared lexicographically; the first items are compared; if they are the same then the second items are compared, and so on.
This allows us to adjust our code to account for both age and name. But remember to put the more significant member first!
|
|
With this, we can sort our objects by their attribute values. But we can do better.
attrgetter()
operator.attrgetter()
is a higher-order function; it takes one-or-more attribute names, and returns a function that can be used to extract those named attributes from an object.
|
|
We can use this to replace our previous lambda, and get:
|
|
Which, to me, seems as straight-forward as can be. I really enjoy the way different language and library features combine to create such beautiful patterns.