cardinal_pythonlib.sort


Original code copyright (C) 2009-2022 Rudolf Cardinal (rudolf@pobox.com).

This file is part of cardinal_pythonlib.

Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.


Support functions for sorting.

class cardinal_pythonlib.sort.MinType[source]

An object that compares less than anything else.

cardinal_pythonlib.sort.atoi(text: str) int | str[source]

Converts strings to integers if they’re composed of digits; otherwise returns the strings unchanged. One way of sorting strings with numbers; it will mean that "11" is more than "2".

class cardinal_pythonlib.sort.attrgetter_nonesort(attr, *attrs)[source]

Modification of operator.attrgetter. Returns an object’s attributes, or the mintype_singleton if the attribute is None.

class cardinal_pythonlib.sort.methodcaller_nonesort(**kwargs)[source]

As per attrgetter_nonesort (q.v.), but for methodcaller.

cardinal_pythonlib.sort.natural_keys(text: str) List[int | str][source]

Sort key function. Returns text split into string/number parts, for natural sorting; as per https://stackoverflow.com/questions/5967500/how-to-correctly-sort-a-string-with-a-number-inside

Example (as per the source above):

>>> from cardinal_pythonlib.sort import natural_keys
>>> alist=[
...     "something1",
...     "something12",
...     "something17",
...     "something2",
...     "something25",
...     "something29"
... ]
>>> alist.sort(key=natural_keys)
>>> alist
['something1', 'something2', 'something12', 'something17', 'something25', 'something29']