pola-rs/polars · error · TypeError

reduce_balanced() of empty iterable

Error message

reduce_balanced() of empty iterable

What it means

reduce_balanced performs a tree-shaped reduction and mirrors functools.reduce semantics, so like reduce it raises TypeError when given an empty iterable — there is no identity element to start the balanced reduction from.

Solutions

  1. Check the list is non-empty before concat: if frames: pl.concat(frames).
  2. Provide an explicit empty frame fallback, e.g. pl.concat(frames or [pl.DataFrame()]).
  3. Guard with a sentinel: return pl.LazyFrame() when no inputs were collected.
  4. Fix the upstream filtering/loop that produced zero items if empty is unexpected.

Example fix

// before
result = pl.concat(frames)
// after
result = pl.concat(frames) if frames else pl.DataFrame()
Defensive patterns

Strategy: validation

Validate before calling

def require_non_empty(items):
    if not items:
        raise ValueError("need at least one frame to combine")
    return items

Try / catch

try:
    result = pl.concat(frames)
except TypeError as e:
    if "empty iterable" in str(e):
        result = pl.DataFrame()
    else:
        raise

Prevention

When it happens

Trigger: Calling pl.concat([]), pl.DataFrame(...) concatenations, union/merge_sorted with an empty list of frames, or directly calling reduce_balanced(f, []) — any empty input list routed to a balanced reduce.

Common situations: Building a list of DataFrames/LazyFrames in a loop that matched nothing, then concatenating the empty list.

Understand the failure class

Background: "must not be empty", "cannot be empty" — required-field validation errors across open-source libraries — this error's family across 41 libraries.

Related errors


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

Appendix: source

Thrown at py-polars/src/polars/_utils/reduce_balanced.py:13

from collections.abc import Callable, Iterable
from typing import TypeVar

T = TypeVar("T")


def reduce_balanced(function: Callable[[T, T], T], iterable: Iterable[T]) -> T:
    """Applies a reduction in a balanced tree pattern."""
    values = list(iterable)

    if not values:
        msg = "reduce_balanced() of empty iterable"
        raise TypeError(msg)

    if len(values) == 1:
        return values.pop()

    stack = [(0, len(values))]

    i = 0

    while i < len(stack):
        offset, length = stack[i]
        half = -(length // -2)

        if length > 3:
            stack.append((offset + half, length - half))

        if length > 2:
            stack.append((offset, half))

View on GitHub (pinned to fe841f959e)