[Python-Dev] Function to handle None in sort operation, was Re: python 3 niggle: None < 1 raises TypeError
Peter Otten
__peter__ at web.de
Fri Feb 14 13:01:13 CET 2014
M.-A. Lemburg wrote:
> IMO, it was a mistake to have None return a TypeError in
> comparisons, since it makes many typical data operations
> fail, e.g.
>
> Python2:
>>>> l = [1,2,None,4,5,None,6]
>>>> l.sort()
>>>> l
> [None, None, 1, 2, 4, 5, 6]
>
> Python3:
>>>> l = [1,2,None,4,5,None,6]
>>>> l.sort()
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> TypeError: unorderable types: NoneType() < int()
While it is trivial to fix
>>> sorted([1,2,None,4,5,None,6],
... key=lambda x: (x is None, x))
[1, 2, 4, 5, 6, None, None]
maybe the key should be given a name like functools.none_first/none_last in
order to offer a standard approach?
On the other hand I'm not sure I like
none_last(x) < none_last(y)
More information about the Python-Dev
mailing list