Functional Weave
Code in Python

units.parse-quantity

Parse "2.5 kg", "1,200 m" or "12 ft 6 in" into an exact decimal value and a canonical unit symbol, strictly.

1.0.0 · published 2026-10-03 by charlie · Anterra

Pinned by 31 tests, run in TypeScript, Python and Rust.

What it does

Turns what a person typed into a value and a canonical unit that `units.convert` accepts: `"2.5 kg"`, `"1,200 m"`, `"12 ft 6 in"`, `"5'11\""`. The value is decimal text, never a float, so nothing is lost between parsing and converting.

## Grammar

For example

  • parse_quantity(2.5 kg) → value 2.5, unit kg, dimension mass a decimal and a symbol
  • parse_quantity(1,200 m) → value 1200, unit m, dimension length thousands separators are removed
  • parse_quantity(12 ft 6 in) → value 150, unit in, dimension length feet and inches sum exactly into inches

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 parse_quantity(text: str) -> Quantity
textstringa number and a unit, or a compound such as "5 lb 3 oz" (largest unit first)
returnsQuantitya compound is summed exactly into its last (smallest) unit

The type it declares, generated into your project

@dataclass(frozen=True)
class Quantity:
    """A parsed quantity, ready to hand to units.convert."""

    #: plain decimal text: commas removed, trailing zeros trimmed
    value: str
    #: canonical units.convert symbol, e.g. "in", "gal_us", "degC"
    unit: str
    #: length, mass, area, volume, temperature or energy
    dimension: str

Your code names it in one line, in the file that uses it

from fune.units.parse_quantity import parse_quantity  # units.parse-quantity@^1
impl/python.py · 170 lines · open · raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

from typing import List, Tuple

from .units_convert_data import UNITS, UnitDefinition  ← units.convert’s rule data (^1.0.0) · built alongside by fune
from .units_parse_quantity_data import UNIT_ALIASES  ← this capability’s own data, compiled from data/aliases.json into the same file by fune build
from .units_parse_quantity_types import Quantity

MAX_DIGITS = 15

# Explicit sets rather than str.isspace()/str.lower(): those differ from the
# other languages on non-ASCII input, and these must not.
_SPACE = " \t\n\r"
_DIGITS = "0123456789"
_LOWER = str.maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")


def _lower(s: str) -> str:
    return s.translate(_LOWER)


def _all_digits(s: str) -> bool:
    return len(s) > 0 and all(c in _DIGITS for c in s)


def _trim(s: str) -> str:
    return s.strip(_SPACE)


def _well_grouped(whole: str) -> bool:
    if "," not in whole:
        return _all_digits(whole)
    groups = whole.split(",")
    return 1 <= len(groups[0]) <= 3 and _all_digits(groups[0]) and all(len(g) == 3 and _all_digits(g) for g in groups[1:])


def _parse_number(written: str) -> Tuple[int, str]:
    pieces = written.split(".")
    plain = written.replace(",", "")
    plain_pieces = plain.split(".")
    plain_ok = len(plain_pieces) <= 2 and _all_digits(plain_pieces[0]) and (len(plain_pieces) == 1 or _all_digits(plain_pieces[1]))
    ok = len(pieces) <= 2 and _well_grouped(pieces[0]) and (len(pieces) == 1 or _all_digits(pieces[1]))
    if not ok:
        if "," in written and plain_ok:
            raise ValueError('bad thousands grouping in "%s"' % (written,))
        raise ValueError('malformed number "%s"' % (written,))
    whole = plain_pieces[0].lstrip("0")
    fraction = (plain_pieces[1] if len(plain_pieces) > 1 else "").rstrip("0")
    if len((whole + fraction).lstrip("0")) > MAX_DIGITS or len(fraction) > MAX_DIGITS:
        raise ValueError(
            'number "%s" has too many digits: at most 15 significant digits and 15 decimal places' % (written,)
        )
    return int(whole) if whole else 0, fraction


def _unit_by_symbol(symbol: str) -> UnitDefinition:
    for u in UNITS:
        if u.symbol == symbol:
            return u
    # Only reachable if the alias table and units.convert drift apart.
    raise ValueError('alias table names unit "%s", which units.convert does not define' % (symbol,))


def _resolve_unit(text: str) -> UnitDefinition:
    for u in UNITS:
        if u.symbol == text:
            return u
    for a in UNIT_ALIASES:
        if a.alias == text:
            if a.symbol is None:
                raise ValueError('ambiguous unit "%s": use %s' % (text, a.choices))
            return _unit_by_symbol(a.symbol)
    # Case-insensitive fallback, so "KG" and "Feet" work. Where two spellings
    # differ only in case and mean different things ("cal" and food "Cal"),
    # the ambiguity wins rather than a guess.
    lower = _lower(text)
    for a in UNIT_ALIASES:
        if a.symbol is None and _lower(a.alias) == lower:
            raise ValueError('ambiguous unit "%s": use %s' % (text, a.choices))
    symbols: List[str] = []
    for u in UNITS:
        if _lower(u.symbol) == lower and u.symbol not in symbols:
            symbols.append(u.symbol)
    for a in UNIT_ALIASES:
        if a.symbol is not None and _lower(a.alias) == lower and a.symbol not in symbols:
            symbols.append(a.symbol)
    if len(symbols) == 1:
        return _unit_by_symbol(symbols[0])
    if len(symbols) > 1:
        raise ValueError('ambiguous unit "%s": letter case matters, use %s' % (text, " or ".join(symbols)))
    raise ValueError('unknown unit "%s"' % (text,))


def _format(negative: bool, whole: int, fraction: str) -> str:
    text = str(whole) + ("." + fraction if fraction else "")
    return "-" + text if negative and (whole != 0 or fraction) else text


def parse_quantity(text: str) -> Quantity:
    """Parse a written quantity into an exact decimal value and a canonical unit.

    A compound such as "12 ft 6 in" is summed into its last unit ("150" in)
    using exact whole-number ratios, which is why mixing systems ("1 ft 2 cm")
    is refused rather than approximated.
    """
    if not isinstance(text, str):
        raise TypeError("quantity text must be a string")
    src = _trim(text)
    if src == "":
        raise ValueError("quantity text is empty")

    negative = False
    parts: List[Tuple[str, int, str, UnitDefinition]] = []
    i = 0
    n = len(src)
    while i < n:
        while i < n and src[i] in _SPACE:
            i += 1
        start = i
        if i < n and src[i] == "-":
            if parts:
                raise ValueError('only the first number may be negative: "%s"' % (src,))
            negative = True
            i += 1
        number_start = i
        while i < n and (src[i] in _DIGITS or src[i] in ",."):
            i += 1
        written = src[number_start:i]
        if written == "":
            raise ValueError('expected a number at "%s"' % (src[start:],))
        whole, fraction = _parse_number(written)
        unit_start = i
        while i < n and src[i] not in _DIGITS and src[i] != "-":
            i += 1
        unit_text = " ".join(t for t in _trim(src[unit_start:i]).replace("\t", " ").replace("\n", " ").replace("\r", " ").split(" ") if t)
        if unit_text == "":
            raise ValueError('missing unit after "%s"' % (written,))
        parts.append((written, whole, fraction, _resolve_unit(unit_text)))

    _, last_whole, last_fraction, last_unit = parts[-1]
    if len(parts) == 1:
        return Quantity(value=_format(negative, last_whole, last_fraction), unit=last_unit.symbol, dimension=last_unit.dimension)

    for k in range(1, len(parts)):
        prev = parts[k - 1][3]
        cur = parts[k][3]
        if cur.dimension != prev.dimension:
            raise ValueError(
                "cannot combine %s (%s) and %s (%s) in one quantity" % (prev.symbol, prev.dimension, cur.symbol, cur.dimension)
            )
        if cur.dimension == "temperature":
            raise ValueError('temperatures cannot be compound: "%s"' % (src,))
        if cur.symbol == prev.symbol:
            raise ValueError('unit "%s" appears twice in "%s"' % (cur.symbol, src))
        if cur.factor_numerator * prev.factor_denominator >= prev.factor_numerator * cur.factor_denominator:
            raise ValueError(
                'units must run from largest to smallest: "%s" cannot come before "%s"' % (prev.symbol, cur.symbol)
            )

    total = last_whole
    for _, whole, fraction, unit in parts[:-1]:
        if fraction:
            raise ValueError('only the last number of a compound quantity may have a fraction: "%s"' % (src,))
        num = unit.factor_numerator * last_unit.factor_denominator
        den = unit.factor_denominator * last_unit.factor_numerator
        if num % den != 0:
            raise ValueError(
                "cannot combine %s and %s exactly: 1 %s is not a whole number of %s"
                % (unit.symbol, last_unit.symbol, unit.symbol, last_unit.symbol)
            )
        total += whole * (num // den)
    return Quantity(value=_format(negative, total, last_fraction), unit=last_unit.symbol, dimension=last_unit.dimension)

Install

fune build

With that line in your source, in a Python project (language python in fune.project), fune build resolves it and its 1 dependency, 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 units.parse-quantity
Download for Python units.parse-quantity-1.0.0-python.fune · 30,662 bytes sha256 9c978616cc0cc4755e18aa6a4f19f500fa7643f9a0cf9360b5dd6831924fde40

The manifest, vectors and README with only the Python implementation. Install it without the registry with fune add ./units.parse-quantity-1.0.0-python.fune, or fetch it from a terminal with fune pull units.parse-quantity@1.0.0:python.

The whole function, every language, is one file too: units.parse-quantity-1.0.0.fune, 48,085 bytes, sha256 8edaf9580576a532d30ec6a175c43a336e2e53ee57d48381fc833377b290fa8c. 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 units.parse-quantity

after — your function gets the result and the arguments, and returns the final result.

# fune: after units.parse-quantity

replace — inside this capability’s code only, calls to a dependency go to your function, with the same signature. Other capabilities that use it are unaffected; write in * to replace it everywhere.

# fune: replace units.convert in units.parse-quantity

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 units.parse-quantity --steps.

# fune: step units.parse-quantity 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.

CaseArgumentsExpected
a decimal and a symbol 2.5 kg → value 2.5, unit kg, dimension mass
thousands separators are removed 1,200 m → value 1200, unit m, dimension length
feet and inches sum exactly into inches 12 ft 6 in → value 150, unit in, dimension length
prime and double-prime marks 5'11" → value 71, unit in, dimension length
a fraction on the last part is kept 5 ft 11.5 in → value 71.5, unit in, dimension length
pounds and ounces 5 lb 3 oz → value 83, unit oz, dimension mass
stones and pounds 11 st 4 lb → value 158, unit lb, dimension mass
metric compounds work too 1 m 5 cm → value 105, unit cm, dimension length
a negative sign applies to the whole compound -5 ft 3 in → value -63, unit in, dimension length
word units in any letter case, trailing zeros trimmed 2.50 Kilograms → value 2.5, unit kg, dimension mass
Show the other 21 tests
CaseArgumentsExpected
degree sign temperature, negative -40 °F → value -40, unit degF, dimension temperature
grouped digits with a fraction 12,345,678.90 mL → value 12345678.9, unit mL, dimension volume
a two-word unit 8 US fl oz → value 8, unit floz_us, dimension volume
no space between number and unit, leading zeros dropped 007kWh → value 7, unit kWh, dimension energy
negative zero is zero -0.0 kg → value 0, unit kg, dimension mass
square feet 3 sq ft → value 3, unit ft2, dimension area
empty text → error: quantity text is empty
a unit with no number kg → error: expected a number at "kg"
a number with no unit 12 → error: missing unit after "12"
bad thousands grouping 1,20 m → error: bad thousands grouping in "1,20"
two decimal points 1.2.3 m → error: malformed number "1.2.3"
unknown unit 3 furlongs → error: unknown unit "furlongs"
a bare gallon is ambiguous 2 gal → error: ambiguous unit "gal": use gal_us or gal_imp
food Calorie is not the calorie symbol, whatever the case 250 CAL → error: ambiguous unit "CAL": use cal (thermochemical calorie) or kcal (food Calorie)
smallest unit first is refused 6 in 12 ft → error: units must run from largest to smallest: "in" cannot come before "ft"
mixed dimensions are refused 5 ft 3 lb → error: cannot combine ft (length) and lb (mass) in one quantity
mixed systems cannot sum exactly 1 ft 2 cm → error: cannot combine ft and cm exactly: 1 ft is not a whole number of cm
a fraction before the last part is refused 5.5 ft 3 in → error: only the last number of a compound quantity may have a fraction
a minus sign inside a compound is refused 5 ft -3 in → error: only the first number may be negative
temperatures are never compound 10 degC 5 K → error: temperatures cannot be compound
more than 15 significant digits 1234567890123456 m → error: has too many digits

More from the author

One or more parts separated by whitespace; each part is a number, optional whitespace, then a unit. The unit runs until the next digit, so two-word units ("fl oz", "sq ft", "US gallon") work.

- Numbers are ASCII digits with an optional `.` fraction. Thousands separators are allowed only as strict groups of three (`1,200`, `12,345,678`); `1,20` is refused rather than guessed at, because in half the world it means 1.20. At most 15 significant digits and 15 decimal places, as in `units.convert`. - A leading `-` is allowed on the first number only, and negates the whole quantity: `-5 ft 3 in` is -63 in. - The value comes back normalised: commas removed, leading zeros and trailing fractional zeros trimmed, and `-0` written as `0`.

## Units

A unit is matched first as a `units.convert` symbol (`kg`, `gal_us`, `degC`), then as an alias from `data/aliases.json` (`kilograms`, `lbs`, `feet`, `'`, `°C`, `sq ft`), then both again ignoring ASCII letter case (`KG`, `Feet`). Only ASCII letters fold, so the answer is the same in every language.

Words that mean different things in different places are refused with the choices spelled out, instead of silently picking one: `gal`, `pint`, `quart`, `fl oz` (US or imperial), `cup`, `ton` (tonne, short or long) and `Cal`/`calorie` (a food Calorie is a kilocalorie). The case-insensitive step never hides this: `CAL` is ambiguous even though `cal` is a symbol. A bare `oz` is the avoirdupois ounce of mass; say `US fl oz` for volume.

Every alias names a symbol that `units.convert` defines; the implementation reads `units.convert`'s own table, so the two cannot drift apart.

## Compound quantities

`12 ft 6 in` is returned as `150 in`: the parts are summed exactly into the last, smallest unit. For that to be exact, the rules are strict:

- every part has the same dimension, and temperatures are never compound; - units run from largest to smallest and never repeat; - only the last number may have a fraction (`5 ft 11.5 in`, not `5.5 ft 3 in`); - each earlier unit must be a whole number of the last one, so `1 ft 2 cm` (30.48 cm per foot) is refused rather than approximated.

Files

PathBytes
README.md2,421
data/aliases.json11,467
impl/python.py7,089
impl/rust.rs9,215
impl/typescript.ts7,482
vectors.json4,148