Skip to content

Units

to_pint wraps a reading's values in pint quantities for unit-aware downstream math.

dtollib.units

:func:to_pint — best-effort unit-name → pint-compatible string conversion.

Pint is not a runtime dependency of dtollib. This module returns plain strings that pint accepts ("degC", "V", "K", ...) so downstream consumers who do use pint can parse them via pint.UnitRegistry().Unit().

Lossy by design — same rule as the sibling libraries. None means "no mapping known"; callers should treat that as a passthrough hint rather than an error.

to_pint

to_pint(unit)

Return a pint-compatible unit string for unit, or None.

Accepts
  • NoneNone.
  • A string already in pint form ("degC", "V", ...) — passed through unchanged when it's in the known set; otherwise returned as-is so unfamiliar units don't get silently dropped.

Lossy by design: no tuple, no discriminator, no exception on unknown units — same contract as the sibling libraries.

Source code in src/dtollib/units.py
def to_pint(unit: object) -> str | None:
    """Return a pint-compatible unit string for ``unit``, or ``None``.

    Accepts:
        - ``None`` → ``None``.
        - A string already in pint form (``"degC"``, ``"V"``, ...) — passed
          through unchanged when it's in the known set; otherwise returned
          as-is so unfamiliar units don't get silently dropped.

    Lossy by design: no tuple, no discriminator, no exception on unknown
    units — same contract as the sibling libraries.
    """
    if unit is None:
        return None
    if isinstance(unit, str):
        return _STRING_PASSTHROUGH.get(unit, unit)
    # Last-ditch: enums and similar objects often expose .name as a SHOUTING
    # string. We don't try to be clever; let callers handle the unknown case.
    name = getattr(unit, "name", None)
    if isinstance(name, str):
        return _STRING_PASSTHROUGH.get(name)
    return None