You want to sort based on two properties:
- First of all, is there a date
- Secondly, date (if present)
You can express your intention in a simple way, sorting by tuple where
- the first element of the tuple indicates whether the date is
None and - the second element of the tuple is the date itself.
list_of_objects.sort(key=lambda x: (x.date is None, x.date), reverse=True)
This approach bypasses the type error you get, because the comparison between tuples is done lazily-right lazily. The second element of the tuple is not compared if the first elements are not equal.
Here are a few examples to demonstrate the concept:
>>> xs = [None, 1, 3, None, 2] >>> sorted(xs, key=lambda x: (x is None, x)) [1, 2, 3, None, None] >>> sorted(xs, key=lambda x: (x is not None, x)) [None, None, 1, 2, 3] >>> sorted(xs, key=lambda x: (x is None, x), reverse=True) [None, None, 3, 2, 1] >>> sorted(xs, key=lambda x: (x is not None, x), reverse=True) [3, 2, 1, None, None]
Chris martin
source share