I'm trying to sort a list of objects using
my_list.sort(key=operator.attrgetter(attr_name))
but if any of the list items has attr = None instead of attr = 'whatever',
then I get a TypeError: unorderable types: NoneType() < str()
In Py2 it wasn't a problem. How do I handle this in Py3?
The ordering comparison operators are stricter about types in Python 3, as described here:
Python 2 sorts
Nonebefore any string (even empty string):In Python 3 any attempts at ordering
NoneTypeinstances result in an exception:The quickest fix I can think of is to explicitly map
Noneinstances into something orderable like"":If you want to sort your data while keeping it intact, just give
sorta customizedkeymethod: