[Python-Dev] Function to handle None in sort operation, was Re: python 3 niggle: None < 1 raises TypeError

2014年2月14日 04:03:00 -0800

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)
_______________________________________________
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com

Reply via email to