Tim Peters wrote:

[Greg Ewing]

often
one wants to sort a collection of objects having
keys that can take on null values.

Perhaps that's often true of your code, but it's never been true of mine.

It's fairly common in accounting circles. I have a
collection of invoices, each of which can have a due
date specified, but doesn't have to. I want to sort
the invoices by due date. It's not particularly
important whether the missing dates sort first or
last, but it *is* important that the sort *not blow
up*.

Dates seem to be a particularly irksome case. Here's
one suggestion from StackOverflow for dealing with
the problem:

   import datetime
   mindate = datetime.date(datetime.MINYEAR, 1, 1)

   def getaccountingdate(x):
     return x['accountingdate'] or mindate

   results = sorted(data, key=getaccountingdate)

That's a ridiculous amount of boilerplate for doing
something that ought to be straightforward.

If you don't want to touch comparison in general,
how about an option to sort()?

  results = sorted(invoices, key=attrgetter('duedate'), none='first')

I have a hard time
imagining why I'd _want_ to sort a list of objects with "null or
missing" keys, instead of filtering such garbage out of the list first

A piece of data is *not* garbage just because an optional
part of it is not specified.

--
Greg
_______________________________________________
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com

Reply via email to