Skip to content

linexcel.values

linexcel.values

What a cell value is, once something has read it.

The engine, the file's own cache and a linked workbook each hand values back in their own shape: a Rust error object, a float that is really a date, a string that is really an error code. This module is the one place that decides what such a thing means: whether it counts as computed, whether two readings of it agree, and how it is written down for the report.

Kept apart from the reading (:mod:linexcel.loader) and from the reasoning (:mod:linexcel.analyzer) because both need these answers and neither owns them.

SpreadsheetError

Bases: str

Error text with its source type retained across external-workbook reads.

Source code in src/linexcel/values.py
class SpreadsheetError(str):
    """Error text with its source type retained across external-workbook reads."""

serial_to_date_text

serial_to_date_text(
    serial: Any, epoch_1904: bool = False
) -> str | None

Convert an Excel serial number to YYYY-MM-DD, or None if it is not a date.

Source code in src/linexcel/values.py
def serial_to_date_text(serial: Any, epoch_1904: bool = False) -> str | None:
    """Convert an Excel serial number to ``YYYY-MM-DD``, or None if it is not a date."""
    if isinstance(serial, bool) or not isinstance(serial, (int, float)):
        return None
    days = float(serial)
    if days != days or days in (float("inf"), float("-inf")):
        return None
    if epoch_1904:
        base = EXCEL_EPOCH_1904
    else:
        if 0 <= days < 1 or 60 <= days < 61:
            return None
        # Negative cached serials use the unshifted epoch, as the workbook
        # readers do. Only Jan/Feb 1900 need the phantom-leap-day correction.
        base = EPOCH_EARLY_1900 if 1 <= days < 60 else EXCEL_EPOCH_1900
    try:
        # Only whole days determine the date. timedelta rounds fractions to
        # microseconds, which could otherwise move a value across midnight.
        return (base + datetime.timedelta(days=math.floor(days))).date().isoformat()
    except (OverflowError, ValueError):
        return None

serial_to_time_text

serial_to_time_text(serial: Any) -> str | None

A fraction of one Excel day as a timezone-free time of day.

Cached times are read at millisecond precision. Keep the date component meaningful: 1.5 days must not silently become the same value as noon.

Source code in src/linexcel/values.py
def serial_to_time_text(serial: Any) -> str | None:
    """A fraction of one Excel day as a timezone-free time of day.

    Cached times are read at millisecond precision. Keep the date component
    meaningful: 1.5 days must not silently become the same value as noon.
    """
    if isinstance(serial, bool) or not isinstance(serial, (int, float)):
        return None
    if not math.isfinite(serial) or not 0 <= serial < 1:
        return None
    milliseconds = round(float(serial) * 86_400_000)
    if milliseconds >= 86_400_000:
        return None
    hours, remainder = divmod(milliseconds, 3_600_000)
    minutes, remainder = divmod(remainder, 60_000)
    seconds, milliseconds = divmod(remainder, 1000)
    return datetime.time(hours, minutes, seconds, milliseconds * 1000).isoformat()

temporal_serials_agree

temporal_serials_agree(left: float, right: float) -> bool

Compare Excel day serials with the cache's absolute 0.5 ms precision.

Source code in src/linexcel/values.py
def temporal_serials_agree(left: float, right: float) -> bool:
    """Compare Excel day serials with the cache's absolute 0.5 ms precision."""
    return (
        not isinstance(left, bool)
        and not isinstance(right, bool)
        and math.isfinite(left)
        and math.isfinite(right)
        and math.isclose(left, right, rel_tol=0, abs_tol=0.0005 / 86400)
    )

readings_agree

readings_agree(
    recalculated: Any,
    stored: Any,
    date_text: str | None,
    *,
    recalculated_is_error: bool | None = None,
    stored_is_error: bool | None = None,
    stored_is_text: bool = False,
    epoch_1904: bool | None = None,
    date_formatted: bool = False,
) -> str

How the two readings of one cell relate: same, format or differ.

One rule, in one place. The report used to hold two: Python compared values for the warnings and returned "no difference" for every pair of strings, missing a recalculated non over a stored oui, while the viewer compared the rendered text and called any difference a disagreement, which is what made a French workbook light up red over 6,7 €.

format is the middle answer neither of them had: the same value, spelt with the separators of whatever saved the file. Both readings are still shown; only the verdict softens.

stored_is_text identifies a literal cache string before serialization. Otherwise date metadata may describe a serialized temporal cache, as in older report callers; that compatibility does not prove a literal's type. epoch_1904 supplies the workbook calendar when day zero has no date label. date_formatted preserves temporal precision for numeric date or duration caches, including Excel's fictitious 1900 leap day and elapsed durations beyond Python's range. It does not assign a calendar label to a duration.

Source code in src/linexcel/values.py
def readings_agree(
    recalculated: Any,
    stored: Any,
    date_text: str | None,
    *,
    recalculated_is_error: bool | None = None,
    stored_is_error: bool | None = None,
    stored_is_text: bool = False,
    epoch_1904: bool | None = None,
    date_formatted: bool = False,
) -> str:
    """How the two readings of one cell relate: ``same``, ``format`` or ``differ``.

    One rule, in one place. The report used to hold two: Python compared
    values for the warnings and returned "no difference" for every pair of
    strings, missing a recalculated ``non`` over a stored ``oui``, while the
    viewer compared the rendered text and called any difference a
    disagreement, which is what made a French workbook light up red over
    ``6,7 €``.

    ``format`` is the middle answer neither of them had: the same value, spelt
    with the separators of whatever saved the file. Both readings are still
    shown; only the verdict softens.

    ``stored_is_text`` identifies a literal cache string before serialization.
    Otherwise date metadata may describe a serialized temporal cache, as in
    older report callers; that compatibility does not prove a literal's type.
    ``epoch_1904`` supplies the workbook calendar when day zero has no date label.
    ``date_formatted`` preserves temporal precision for numeric date or duration
    caches, including Excel's fictitious 1900 leap day and elapsed durations
    beyond Python's range. It does not assign a calendar label to a duration.
    """
    if stored_is_text and (
        date_text is not None
        or isinstance(recalculated, (datetime.date, datetime.time, datetime.timedelta))
    ):
        return "differ"
    if (
        recalculated_is_error is not None
        and stored_is_error is not None
        and recalculated_is_error != stored_is_error
    ):
        return "differ"
    if isinstance(stored, datetime.timedelta) and isinstance(
        recalculated, datetime.timedelta
    ):
        # Subtract before converting to seconds: long durations must retain
        # microsecond precision, and negative durations keep their sign.
        try:
            difference = abs(recalculated - stored)
        except OverflowError:
            # Opposite timedelta limits are farther apart than a timedelta
            # can represent, and therefore certainly exceed cache rounding.
            return "differ"
        return (
            "same" if difference <= datetime.timedelta(microseconds=500) else "differ"
        )
    if isinstance(stored, datetime.timedelta) and isinstance(
        recalculated, (int, float)
    ):
        # Elapsed formats store a duration, not a date or a time of day.
        # Retain whole and negative days, and tolerate only cache rounding
        # to milliseconds, independent of the duration's magnitude or epoch.
        return (
            "same"
            if not isinstance(recalculated, bool)
            and math.isfinite(recalculated)
            and math.isclose(
                # Remove whole days before converting: absolute totals lose
                # sub-millisecond precision for large, unchanged durations.
                (recalculated - stored.days) * 86400,
                stored.seconds + stored.microseconds / 1_000_000,
                rel_tol=0,
                abs_tol=0.0005,
            )
            else "differ"
        )
    time_agreement = _time_agreement(recalculated, stored, date_text)
    if time_agreement is not None:
        return time_agreement
    datetime_agreement = _serial_datetime_agreement(
        recalculated, stored, date_text, epoch_1904
    )
    if datetime_agreement is not None:
        return datetime_agreement
    typed_datetime_agreement = _typed_datetime_agreement(
        recalculated, stored, date_text
    )
    if typed_datetime_agreement is not None:
        return typed_datetime_agreement
    if (
        date_formatted
        and isinstance(recalculated, (int, float))
        and isinstance(stored, (int, float))
        and not isinstance(recalculated, bool)
        and not isinstance(stored, bool)
    ):
        return "same" if temporal_serials_agree(recalculated, stored) else "differ"
    if _values_differ(recalculated, stored, date_text):
        return "differ"
    error_text = _excel_error_text(recalculated)
    if error_text is not None:
        return "same" if error_text == stored else "differ"
    if isinstance(recalculated, (int, float)) and isinstance(stored, (int, float)):
        return "same"
    if type(recalculated) is not type(stored):
        return "differ"
    left, right = _fmt_value(recalculated), _fmt_value(stored)
    if left == right:
        return "same"
    if (
        isinstance(recalculated, str)
        and isinstance(stored, str)
        and _separators_only(left, right)
    ):
        return "format"
    return "differ"