collections.sort-by
Stably sort records by one key, ascending or descending, with a total order across mixed types.
1.0.0 · published 2026-10-03 by charlie · Anterra
Pinned by 21 tests, run in TypeScript, Python and Rust.
What it does
The sort is stable: records that tie on the key come out in the order they went in, in BOTH directions. Descending negates the comparison rather than reversing the list, so the tied block is not silently flipped - that is what makes sorting by one column and then another compose into the multi-column sort a user expects.
The total order for mixed values is: booleans, then numbers, then strings, and absent values last. Absent values sink to the bottom in both directions, because 'the rows we know nothing about' belong at the end of a descending table as much as an ascending one; reversing them would put the empty rows first, which no one has ever wanted.
For example
sort_by(records ×3, n, asc)→ ×3 ascending by a string keysort_by(records ×3, n, desc)→ ×3 descending by a string keysort_by(records ×3, s, asc)→ ×3 ascending by a number key
The function
The same function in TypeScript, Python and Rust, pinned by the same tests. Pick your language; the choice follows you around the registry.
def sort_by(records: Sequence[Mapping[str, Any]], key: str, direction: SortDirection) -> List[Mapping[str, Any]]
| records | record[] | open JSON-ish maps; shapes may differ between records |
| key | string | the field to order by |
| direction | SortDirection | |
| returns | record[] | a new list; the input is never reordered in place |
The type it declares, generated into your project
SortDirection = Literal["asc", "desc"]
Your code names it in one line, in the file that uses it
from fune.collections.sort_by import sort_by # collections.sort-by@^1
from functools import cmp_to_key
from typing import Any, List, Mapping, Sequence
from .collections_sort_by_types import SortDirection
# The type ranks that give mixed values a total order. Absent sorts last in
# both directions, so it is ranked above every present value and then excluded
# from the direction flip below.
RANK_BOOL = 0
RANK_NUMBER = 1
RANK_STRING = 2
RANK_ABSENT = 3
def _rank_of(value: Any, key: str) -> int:
# Absent and null are the same thing: a document that omits a field and one
# that nulls it mean the same to every reader.
if value is None:
return RANK_ABSENT
# bool before int: in Python True is an int, and ranking it as a number
# would order it against 0 and 1 instead of with the other booleans.
if isinstance(value, bool):
return RANK_BOOL
if isinstance(value, (int, float)):
return RANK_NUMBER
if isinstance(value, str):
return RANK_STRING
raise TypeError('cannot sort by the list or map at "%s"' % (key,))
def _compare_scalars(rank: int, a: Any, b: Any) -> int:
if rank == RANK_STRING:
# Python compares strings by code point, which is the order this
# capability pins; TypeScript spells the same comparison out by hand
# because JavaScript would otherwise compare UTF-16 code units.
return -1 if a < b else (1 if a > b else 0)
if rank == RANK_NUMBER:
return -1 if a < b else (1 if a > b else 0)
return 0 if a == b else (1 if a else -1)
def sort_by(
records: Sequence[Mapping[str, Any]],
key: str,
direction: SortDirection = "asc",
) -> List[Mapping[str, Any]]:
"""Stably sort ``records`` by ``key``, ascending or descending.
Ties keep their input order in both directions, which is what lets a user
sort by one column and then another and get the multi-column sort they
expect rather than a reshuffle.
"""
if isinstance(records, (str, bytes)) or not isinstance(records, (list, tuple)):
raise TypeError("sort_by needs a list of records")
if not isinstance(key, str) or key == "":
raise TypeError("sort_by needs a non-empty key name")
if direction not in ("asc", "desc"):
raise ValueError('direction must be "asc" or "desc", received "%s"' % (direction,))
# Rank every record up front. Raising mid-comparison would make the error
# depend on which comparisons this interpreter's sort happened to perform.
values = [record.get(key) if isinstance(record, dict) else None for record in records]
ranks = [_rank_of(value, key) for value in values]
sign = -1 if direction == "desc" else 1
indexed = list(range(len(records)))
def compare(i: int, j: int) -> int:
ri, rj = ranks[i], ranks[j]
# Absent values sink to the bottom whichever way the sort runs: nobody
# wants the rows they know nothing about at the top of a descending table.
if ri == RANK_ABSENT or rj == RANK_ABSENT:
if ri == rj:
return 0
return 1 if ri == RANK_ABSENT else -1
if ri != rj:
base = -1 if ri < rj else 1
else:
base = _compare_scalars(ri, values[i], values[j])
return base * sign
indexed.sort(key=cmp_to_key(compare))
return [records[i] for i in indexed]Install
fune build
With that line in your source, in a Python project (language python in fune.project), fune build resolves it and nothing else, pins them in fune.lock, downloads only the Python package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. Or pin a range in fune.project and build in one step:
fune add collections.sort-by
The manifest, vectors and README with only the Python implementation. Install it without the registry with fune add ./collections.sort-by-1.0.0-python.fune, or fetch it from a terminal with fune pull collections.sort-by@1.0.0:python.
The whole function, every language, is one file too: collections.sort-by-1.0.0.fune, 19,865 bytes, sha256 64f59dd149f5eee9c1e84e5a62ff365767cda76a85825b539a3a053a40a080c6. It installs into a project of any language.
Customise it in your app
The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.
before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.
# fune: before collections.sort-by
after — your function gets the result and the arguments, and returns the final result.
# fune: after collections.sort-by
replace — it requires no other capability, so there is no dependency to replace.
step — your function runs at a numbered point inside the function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show collections.sort-by --steps.
# fune: step collections.sort-by after <n|label>
Tests
A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.
| Case | Arguments | Expected | |
|---|---|---|---|
| ascending by a string key | records ×3, n, asc | → | ×3 |
| descending by a string key | records ×3, n, desc | → | ×3 |
| ascending by a number key | records ×3, s, asc | → | ×3 |
| descending by a number key | records ×3, s, desc | → | ×3 |
| ties keep their input order ascending | records ×4, s, asc | → | ×4 |
| ties keep their input order descending too: the tied block is not flipped | records ×4, s, desc | → | ×4 |
| nulls and missing keys sort last ascending, keeping their own order | records ×4, s, asc | → | ×4 |
| nulls stay last descending: the rows we know nothing about never come first | records ×4, s, desc | → | ×4 |
| a list of nothing but absent values comes back in input order | records ×3, s, asc | → | ×3 |
| an empty list sorts to an empty list | , s, asc | → |
Show the other 11 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| a single record is already sorted, in either direction | records ×1, s, desc | → | ×1 |
| mixed types have one total order ascending: booleans, then numbers, then strings | records ×6, v, asc | → | ×6 |
| mixed types reverse cleanly descending | records ×6, v, desc | → | ×6 |
| integers and fractions interleave by value, not by type | records ×4, v, asc | → | ×4 |
| strings compare by code point, so capitals sort before lowercase | records ×4, v, asc | → | ×4 |
| a prefix sorts before the longer string, and accented letters sort after ASCII | records ×4, v, asc | → | ×4 |
| records with different shapes sort on the one field they share | records ×3, n, asc | → | ×3 |
| an unknown direction is an error, not a silent ascending sort | records ×1, s, ascending | → | error: direction must be "asc" or "desc" |
| a list at the sort key has no defensible order | records ×2, s, asc | → | error: list or map |
| a map at the sort key has no defensible order | records ×2, s, asc | → | error: list or map |
| an empty key name is a caller bug | records ×1, , asc | → | error: non-empty key name |
More from the author
A missing key and a null value are the same thing and both sort last.
Strings compare by Unicode code point, spelled out rather than inherited: JavaScript's < compares UTF-16 code units and disagrees with Python and Rust above U+FFFF. Comparison is case-sensitive, so 'Zebra' sorts before 'apple'; lowercase the key first if you want a case-insensitive sort.
A list or a map at the sort key is an error, and it is detected in one pass before sorting starts. Discovering it mid-comparison would make the error depend on which comparisons that language's sort happened to perform.
Files
| Path | Bytes |
|---|---|
| README.md | 1,268 |
| impl/python.py | 3,315 |
| impl/rust.rs | 3,698 |
| impl/typescript.ts | 3,794 |
| vectors.json | 4,914 |