{"record":{"id":"d5246469177196c3","repo":"pandas-dev/pandas","slug":"unable-to-avoid-copy-while-creating-an-array-as-re","errorCode":null,"errorMessage":"Unable to avoid copy while creating an array as requested.","messagePattern":"Unable to avoid copy while creating an array as requested\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/arrow/array.py","lineNumber":1023,"sourceCode":"            remask = functools.partial(pa.array, mask=mask, from_pandas=False)\n            if isinstance(result, tuple):\n                return tuple(type(self)(remask(res)) for res in result)\n            return type(self)(remask(result))\n\n        # Need to wrap np.array results GH#62800\n        result = super().__array_ufunc__(ufunc, method, *inputs, **kwargs)\n        if type(self) is ArrowExtensionArray:\n            # Exclude ArrowStringArray\n            return type(self)._from_sequence(result)\n        return result\n\n    def __array__(\n        self, dtype: NpDtype | None = None, copy: bool | None = None\n    ) -> np.ndarray:\n        \"\"\"Correctly construct numpy arrays when passed to `np.asarray()`.\"\"\"\n        if copy is False:\n            # TODO: By using `zero_copy_only` it may be possible to implement this\n            raise ValueError(\n                \"Unable to avoid copy while creating an array as requested.\"\n            )\n        elif copy is None:\n            # `to_numpy(copy=False)` has the meaning of NumPy `copy=None`.\n            copy = False\n\n        return self.to_numpy(dtype=dtype, copy=copy)\n\n    def __invert__(self) -> Self:\n        # This is a bit wise op for integer types\n        if pa.types.is_integer(self._pa_array.type):\n            return self._from_pyarrow_array(pc.bit_wise_not(self._pa_array))\n        elif pa.types.is_string(self._pa_array.type) or pa.types.is_large_string(\n            self._pa_array.type\n        ):\n            # Raise TypeError instead of pa.ArrowNotImplementedError\n            raise TypeError(\"__invert__ is not supported for string dtypes\")\n        else:","sourceCodeStart":1005,"sourceCodeEnd":1041,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/arrow/array.py#L1005-L1041","documentation":"Raised by ArrowExtensionArray.__array__ when called with copy=False (e.g. np.asarray(arr, copy=False)). PyArrow-backed arrays cannot expose a zero-copy numpy view in general, so requesting copy=False is impossible to satisfy. The implementation deliberately rejects the request rather than silently copying, following NEP 50/__array__ copy semantics.","triggerScenarios":"`np.asarray(arrow_arr, copy=False)`, `np.array(arrow_arr, copy=False)`, or libraries (e.g. newer numpy/sklearn) passing copy=False to __array__. Also `arr.to_numpy(copy=False)` is fine (handled separately) but direct np.asarray with copy=False hits __array__.","commonSituations":"Code optimized to avoid copies passing copy=False unconditionally; sklearn/scipy-style `check_array(copy=False)`; migration to numpy>=2.0 where copy semantics became stricter.","solutions":["Allow a copy: np.asarray(arrow_arr) or np.asarray(arrow_arr, copy=True).","Use arr.to_numpy(copy=None) which maps None to pandas copy semantics.","If you must avoid copies, work with the underlying pyarrow array: arr._pa_array.to_numpy(zero_copy_only=False).","Refactor the caller to not pass copy=False for extension arrays."],"exampleFix":"# before\nnp_arr = np.asarray(arrow_arr, copy=False)  # ValueError\n# after\nnp_arr = np.asarray(arrow_arr)              # copy allowed\n# or\nnp_arr = arrow_arr.to_numpy()               # pandas path","handlingStrategy":"validation","validationCode":"import numpy as np\n\ndef to_numpy_no_fail(arr, copy=None):\n    if copy is False:\n        copy = None  # ArrowExtensionArray cannot zero-copy to numpy\n    return np.asarray(arr, copy=copy) if np.lib.NumpyVersion(np.__version__) >= '2.0.0' else np.asarray(arr)\n\nnp_arr = to_numpy_no_fail(arrow_arr, copy=False)","typeGuard":"def supports_zero_copy_numpy(arr) -> bool:\n    # ArrowExtensionArray never supports copy=False via __array__\n    from pandas.core.arrays.arrow import ArrowExtensionArray\n    return not isinstance(arr, ArrowExtensionArray)","tryCatchPattern":"try:\n    np_arr = np.asarray(arrow_arr, copy=False)\nexcept ValueError as e:\n    if 'avoid copy' in str(e):\n        np_arr = np.asarray(arrow_arr)\n    else:\n        raise","preventionTips":["Never pass copy=False to np.asarray on extension arrays unconditionally.","Use arr.to_numpy(copy=None) for pandas-native copy semantics.","Gate copy=False behind a capability check for numpy interop."],"tags":["pyarrow","numpy-interop","copy-semantics","conversion"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}