pola-rs/polars · error · TypeError

invalid dtype for `ones`; found

Error message

invalid dtype for `ones`; found {dtype}

What it means

Validation in pl.ones: the dtype must be numeric so a unit value (1) can be represented; _one_or_zero_by_dtype returns None for non-numeric/unsupported dtypes (e.g. String, List), triggering this TypeError.

Solutions

  1. Use a numeric or boolean dtype: pl.Int64, pl.Float64, pl.Boolean, etc.
  2. If you need string ones, build with `pl.repeat('1', n, dtype=pl.Utf8)` directly? — no; instead create numeric ones and cast: `pl.ones(n).cast(pl.Utf8)`
  3. Validate dtype against a numeric allowlist before calling

Example fix

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

Strategy: validation

Validate before calling

NUMERIC = (pl.Int8, pl.Int16, pl.Int32, pl.Int64, pl.UInt8, pl.UInt16, pl.UInt32, pl.UInt64, pl.Float32, pl.Float64, pl.Boolean)
if not (isinstance(dtype, pl.DataType) and any(dtype == d for d in NUMERIC)):
    raise TypeError(f'ones requires numeric dtype, got {dtype}')

Type guard

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

Try / catch

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

Prevention

When it happens

Trigger: `pl.ones(n, dtype=pl.Utf8)` or other non-numeric dtypes (e.g. pl.List, pl.Struct, pl.Object, pl.Null).

Common situations: Passing a string dtype expecting '1' strings; generic code parameterized by dtype that can receive non-numeric dtypes.

Related errors


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

Appendix: source

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

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

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

    return repeat(one, n=n, dtype=dtype, eager=eager).alias("ones")


@overload
def zeros(
    n: int | Expr,
    dtype: PolarsDataType = ...,
    *,
    eager: Literal[False] = ...,
) -> Expr: ...


@overload
def zeros(
    n: int | Expr,
    dtype: PolarsDataType = ...,
    *,

View on GitHub (pinned to fe841f959e)