For the sake of simplicity, let's say I have a Person class in Python. This class has fields for firstname, lastname, and dob.
class Person:
def __init__(self, firstname, lastname, dob):
self.firstname = firstname;
self.lastname = lastname;
self.dob = dob;
In some situations I want to sort lists of Persons by lastname followed by firstname followed by dob. In other situations I want to sort first by dob, then by lastname and finally by firstname. And sometimes I just want to sort by firstname.
The naive solution for creating the first comparison function would be something like this:
def comparepeople(person1, person2):
if cmp(person1.lastname, person2.lastname) == 0:
if cmp(person1.firstname, person2.firstname) == 0:
return cmp(person1.dob, person2.dob);
return cmp(person1.firstname, person2.firstname);
return cmp(person1.lastname, person2.lastname);
It would seem like there should be an easy way to define comparison functions like these using a meta-programming approach where all I would need to do is provide the field names in order of precedence instead of writing these very verbose, ugly comparison methods. But I've only started playing with Python recently and haven't found anything like what I'm describing.
So the question is, what is the most Pythonic way to write a comparison function for a class with multiple comparable constituent members?