I am having a hard time coming up with a slick way to handle this sort. I have data coming back from a database read. I want to sort on the accoutingdate. However, accoutingdate may sometimes be null. I am currently doing the following:
results = sorted(results, key=operator.itemgetter('accountingdate'), reverse=True)
But, this bombs with “TypeError: can’t compare datetime.date to NoneType” due to some accoutingdates being null.
What is the “most correct” or “most Pythonic” way to handle this?
Using a
key=function is definitely right, you just have to decide how you want to treat theNonevalues — pick adatetimevalue that you want to treat as the equivalent ofNonefor sorting purposes. E.g.:Just see how much simpler this is than defining a
cmpfunction instead — and if you do some benchmarking you’ll find it’s also significantly faster! There’s no upside at all in using acmpfunction instead of thiskeyfunction, and it would be a bad design choice to do so.