sort_records using a custom comparator
Python
"""Sort records by several keys using an explicit comparator, nulls safe."""
import functools
from typing import Any
def compare_values(left: Any, right: Any, *, nulls_last: bool = True) -> int:
"""Three-way compare that never raises when either side is None."""
if left is None or right is None:
if left is right: # both are None
return 0
return (1 if left is None else -1) * (1 if nulls_last else -1)
if left == right:
return 0
return -1 if left < right else 1
def sort_records(
rows: list[dict[str, Any]],
fields: list[str],
*,
reverse_fields: set[str] | None = None,
nulls_last: bool = True,
) -> list[dict[str, Any]]:
"""Stable priority sort: the first field dominates, later ones break ties."""
descending = reverse_fields or set()
def compare(left: dict[str, Any], right: dict[str, Any]) -> int:
for field in fields:
left_value, right_value = left.get(field), right.get(field)
result = compare_values(left_value, right_value, nulls_last=nulls_last)
if result:
if left_value is None or right_value is None:
return result # keep None out of the reversed ordering
return -result if field in descending else result
return 0
return sorted(rows, key=functools.cmp_to_key(compare))