Skip to content

Sorting tuples containing None raises TypeError in 3.11 #95173

Closed
@jacobtylerwalls

Description

@jacobtylerwalls

Bug report

3.10

>>> sorted([(None, 2), (None, 1)])
[(None, 1), (None, 2)]

3.11.0b4

>>> sorted([(None, 2), (None, 1)])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'NoneType' and 'NoneType'

Sorting lists works fine:

>>> sorted([[None, 2], [None, 1]])
[[None, 1], [None, 2]]

From the release notes, I expect this is due to #29076, however the release notes merely say that the "order of the result may differ", not that comparisons might newly raise TypeError:

Cases of sorting using tuples as keys may be significantly faster
in some cases. This is worth mentioning because, if the tuple
elements don't define a total ordering, the order of the result
may differ from earlier releases. It's generally true that the
result of sorting simply isn't well-defined in the absence of a
total ordering on list elements.

And the issue discussion says this about sorted():

Since very little is defined about the result of sorted() in the absence of a total ordering (just that it's some permutation of the original), that's not surprising.

So while I agree with the sentiment that it's not great to be sorting tuples containing elements without a total ordering, I wonder if the current release note might merit some editing.


Real-life example involved a pattern like:

sorted(iterable, key=attrgetter("optional_member", "required_member"))

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.11only security fixes3.12only security fixesrelease-blockertriagedThe issue has been accepted as valid by a triager.type-bugAn unexpected behavior, bug, or error

    Projects

    Status

    Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions