pola-rs/polars · error · TypeError

invalid input for `copy

Error message

invalid input for `copy`: {copy!r}

What it means

Series.__array__ validates the `copy` keyword strictly: only True, False, or None are accepted (per the dataframe interchange convention). Any other truthy/falsy value (e.g. 1, 0, "yes") raises this TypeError at py-polars/src/polars/series/series.py:1492.

Solutions

  1. Pass a real boolean: `series.__array__(copy=True)` or `copy=False`
  2. Coerce before calling: `copy=bool(copy)` — but ensure it maps to True/False, not 0/1
  3. Omit copy (None) to let polars choose the cheapest path

Example fix

// before
arr = s.__array__(copy=1)  # TypeError
// after
arr = s.__array__(copy=True)
Defensive patterns

Strategy: validation

Validate before calling

if copy is not None and not isinstance(copy, bool):
    raise ValueError("copy must be True, False, or None")
arr = series.__array__(dtype=dtype, copy=copy)

Type guard

def is_bool_flag(copy: object) -> bool:
    return copy is None or isinstance(copy, bool)

Try / catch

try:
    arr = series.__array__(dtype=dtype, copy=copy)
except TypeError as e:
    if "invalid input for `copy`" in str(e):
        arr = series.__array__(dtype=dtype, copy=bool(copy) and True or False)
    else:
        raise

Prevention

When it happens

Trigger: Calling `series.to_numpy()`/`np.asarray(series, ...)` machinery or `series.__array__(dtype, copy=1)` with a non-bool copy value; passing copy from user config where an int was stored.

Common situations: Passing `copy=0`/`copy=1` from YAML/CLI config; older numpy interop code using integer flags; calling __array__ directly in custom converters.

Understand the failure class

Background: "Must be a positive integer", "Invalid value", "Unsupported": the invalid-argument-value error family, when a library rejects the value you pass — this error's family across 35 libraries.

Related errors


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

Appendix: source

Thrown at py-polars/src/polars/series/series.py:1492

        See Also
        --------
        __array_ufunc__
        """
        # Cast String types to fixed-length string to support string ufuncs
        # TODO: Use variable-length strings instead when NumPy 2.0.0 comes out:
        # https://numpy.org/devdocs/reference/routines.dtypes.html#numpy.dtypes.StringDType
        if dtype is None and not self.has_nulls() and self.dtype == String:
            dtype = np.dtype("U")

        if copy is None:
            writable, allow_copy = False, True
        elif copy is True:
            writable, allow_copy = True, True
        elif copy is False:
            writable, allow_copy = False, False
        else:
            msg = f"invalid input for `copy`: {copy!r}"
            raise TypeError(msg)

        arr = self.to_numpy(writable=writable, allow_copy=allow_copy)

        if dtype is not None and dtype != arr.dtype:
            if copy is False:
                # TODO: Only raise when data must be copied
                msg = f"copy not allowed: cast from {arr.dtype} to {dtype} prohibited"
                raise RuntimeError(msg)

            arr = arr.__array__(dtype)

        return arr

    def __array_ufunc__(
        self, ufunc: np.ufunc, method: str_, *inputs: Any, **kwargs: Any
    ) -> Series:
        """Numpy universal functions."""
        if self._s.n_chunks() > 1:

View on GitHub (pinned to fe841f959e)