[Python-Dev] python 3 niggle: None < 1 raises TypeError

Greg Ewing greg.ewing at canterbury.ac.nz
Tue Feb 18 08:35:52 CET 2014


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


More information about the Python-Dev mailing list