pola-rs/polars · error · TypeError

invalid dtype for `zeros`; found

Error message

invalid dtype for `zeros`; found {dtype}

What it means

The zeros() helper could not produce a zero literal for the requested dtype: _one_or_zero_by_dtype(0, dtype) returned None, meaning the dtype does not support a usable zero value (e.g. a non-numeric or otherwise incompatible type). Since the whole function is built around repeating a zero, it raises TypeError naming the offending dtype.

Solutions

  1. Use a numeric or boolean dtype
  2. Create numeric zeros and cast: `pl.zeros(n).cast(target_dtype)` if a cast exists
  3. Gate the dtype with a numeric allowlist before the call

Example fix

// before
pl.zeros(3, dtype=pl.Utf8)
// after
pl.zeros(3, dtype=pl.Int64).cast(pl.Utf8)
Defensive patterns

Strategy: validation

Validate before calling

if dtype in (pl.Utf8, pl.Object, pl.Null, pl.List, pl.Struct):
    raise TypeError(f'zeros requires numeric dtype, got {dtype}')

Type guard

def supports_zeros(dtype) -> bool:
    try:
        from polars.functions.repeat import _one_or_zero_by_dtype
        return _one_or_zero_by_dtype(0, dtype) is not None
    except Exception:
        return False

Try / catch

try:
    s = pl.zeros(n, dtype=dtype)
except TypeError as e:
    if 'invalid dtype for `zeros`' in str(e):
        s = pl.zeros(n, dtype=pl.Int64).cast(dtype)
    else:
        raise

Prevention

When it happens

Trigger: `pl.zeros(n, dtype=pl.Utf8)` or any dtype where `_one_or_zero_by_dtype(0, dtype)` returns None.

Common situations: String/struct placeholders intended as 'zero'; parameterized helper functions fed arbitrary dtypes.

Related errors


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

Appendix: source

Thrown at py-polars/src/polars/functions/repeat.py:299

    See Also
    --------
    repeat
    lit

    Examples
    --------
    >>> pl.zeros(3, pl.Int8, eager=True)
    shape: (3,)
    Series: 'zeros' [i8]
    [
        0
        0
        0
    ]
    """
    if (zero := _one_or_zero_by_dtype(0, dtype)) is None:
        msg = f"invalid dtype for `zeros`; found {dtype}"
        raise TypeError(msg)

    return repeat(zero, n=n, dtype=dtype, eager=eager).alias("zeros")

View on GitHub (pinned to fe841f959e)