src/graphql/pyutils/natural_compare.py
raw| 1 | import re |
| 2 | from typing import Tuple |
| 3 | |
| 4 | from itertools import cycle |
| 5 | |
| 6 | __all__ = ["natural_comparison_key"] |
| 7 | |
| 8 | _re_digits = re.compile(r"(\d+)") |
| 9 | |
| 10 | |
| 11 | def natural_comparison_key(key: str) -> Tuple: |
| 12 | """Comparison key function for sorting strings by natural sort order. |
| 13 | |
| 14 | See: https://en.wikipedia.org/wiki/Natural_sort_order |
| 15 | """ |
| 16 | return tuple( |
| 17 | (int(part), part) if is_digit else part |
| 18 | for part, is_digit in zip(_re_digits.split(key), cycle((False, True))) |
| 19 | ) |