Sorting by attributes that can be None
sorted(items, key=lambda i: i.data.value if i.data else 0)
Use as key a tuple, like (False, value)
. If value is None, then the tuple should be (True, None)
.
Tuples are compared by their first element first, then the second, et cetera. False sorts before True. So all None values will be sorted to the end.
def none_to_end_key(item):
value = item.data.value if item.data else None
return (value is None, value)
sorted(items, key=none_to_end_key)
Will sort all None values to the end.
I see now that you have tagged your question Python-2.7, then this is probably overkill. In Python 3, comparing None to an integer or string raises an exception, so you can't simply sort a list with None and other values, and something like this is needed.
just filter for the None before sorting
sorted(filter(None, items), key=attrgetter('data.value'))