pola-rs/polars · error · ValueError

`unit` must be one of

Error message

`unit` must be one of {'b', 'kb', 'mb', 'gb', 'tb'}, got {unit!r}

What it means

scale_bytes converts a byte size to a human-readable string using a unit keyword. If the unit is not one of b/kb/mb/gb/tb (or their long aliases like 'kilobytes'), it raises ValueError listing the accepted units. It's a strict unit-argument validation.

Solutions

  1. Use one of 'b','kb','mb','gb','tb' (or 'bytes','kilobytes','megabytes','gigabytes','terabytes'), lowercased and trimmed.
  2. Normalize input: unit = unit.strip().lower() before calling.
  3. If you need binary units (KiB/MiB), do the division yourself instead of scale_bytes.

Example fix

// before
scale_bytes(n, 'KiB')
// after
scale_bytes(n, 'kb')  # or n / 1024 for binary KiB
Defensive patterns

Strategy: validation

Validate before calling

unit = unit.strip().lower()
assert unit in {'b','kb','mb','gb','tb'}, f'unsupported unit: {unit!r}'

Type guard

def is_valid_unit(u) -> bool:
    return u in {'b','kb','mb','gb','tb','bytes','kilobytes','megabytes','gigabytes','terabytes'}

Try / catch

try:
    human = scale_bytes(sz, unit)
except ValueError as e:
    if 'unit' in str(e):
        human = scale_bytes(sz, 'b')

Prevention

When it happens

Trigger: Calling the internal scale_bytes (used in repr/table formatting and public helpers) with a unit like 'kib', 'KiB', 'B', 'kb ' with whitespace, or a typo such as 'kilobyte'.

Common situations: Configuring display/str formatting with a custom unit, wrapping scale_bytes in user tooling with nonstandard units, or case/whitespace mistakes.

Understand the failure class

Background: Invalid enum value errors: "Unknown type", "Invalid scope", "must be one of" — when a string is not on the library's allowed list — this error's family across 23 libraries.

Related errors


AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18). Data as JSON: /api/errors/91dc59ffc86ba705. Report an issue: GitHub.

Appendix: source

Thrown at py-polars/src/polars/_utils/various.py:311

@overload
def scale_bytes(sz: Expr, unit: SizeUnit) -> Expr: ...


def scale_bytes(sz: int | Expr, unit: SizeUnit) -> int | float | Expr:
    """Scale size in bytes to other size units (eg: "kb", "mb", "gb", "tb")."""
    if unit in {"b", "bytes"}:
        return sz
    elif unit in {"kb", "kilobytes"}:
        return sz / 1024
    elif unit in {"mb", "megabytes"}:
        return sz / 1024**2
    elif unit in {"gb", "gigabytes"}:
        return sz / 1024**3
    elif unit in {"tb", "terabytes"}:
        return sz / 1024**4
    else:
        msg = f"`unit` must be one of {{'b', 'kb', 'mb', 'gb', 'tb'}}, got {unit!r}"
        raise ValueError(msg)


def _cast_repr_strings_with_schema(
    df: DataFrame, schema: dict[str, PolarsDataType | None]
) -> DataFrame:
    """
    Utility function to cast table repr/string values into frame-native types.

    Parameters
    ----------
    df
        Dataframe containing string-repr column data.
    schema
        DataFrame schema containing the desired end-state types.

    Notes
    -----
    Table repr strings are less strict (or different) than equivalent CSV data, so need

View on GitHub (pinned to fe841f959e)