{"record":{"id":"f7bee161e4c3b9b3","repo":"pandas-dev/pandas","slug":"unable-to-avoid-copy-while-creating-an-array-as-re-f7bee1","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/datetimelike.py","lineNumber":349,"sourceCode":"        -------\n        ndarray[str]\n        \"\"\"\n        raise AbstractMethodError(self)\n\n    def _formatter(self, boxed: bool = False) -> Callable[[object], str]:\n        # TODO: Remove Datetime & DatetimeTZ formatters.\n        return \"'{}'\".format\n\n    # ----------------------------------------------------------------\n    # Array-Like / EA-Interface Methods\n\n    def __array__(\n        self, dtype: NpDtype | None = None, copy: bool | None = None\n    ) -> np.ndarray:\n        # used for Timedelta/DatetimeArray, overwritten by PeriodArray\n        if is_object_dtype(dtype):\n            if copy is False:\n                raise ValueError(\n                    \"Unable to avoid copy while creating an array as requested.\"\n                )\n            return np.array(list(self), dtype=object)\n\n        if copy is True:\n            return np.array(self._ndarray, dtype=dtype)\n\n        result = self._ndarray\n        if self._readonly:\n            result = result.view()\n            result.flags.writeable = False\n        return result\n\n    @overload\n    def __getitem__(self, key: ScalarIndexer) -> DTScalarOrNaT: ...\n\n    @overload\n    def __getitem__(","sourceCodeStart":331,"sourceCodeEnd":367,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/datetimelike.py#L331-L367","documentation":"Raised by DatetimeLikeArrayMixin.__array__ when a caller requests dtype=object together with copy=False. Converting a packed datetime/timedelta/period array to object dtype fundamentally requires materialising Python objects (a copy), so a no-copy request is impossible and pandas surfaces the conflict as ValueError rather than silently ignoring the flag.","triggerScenarios":"np.asarray(datetime_array, dtype=object, copy=False); np.array(arr, dtype=object, copy=False); or any code path that calls __array__ with both object dtype and a false copy flag. NumPy's copy=False (or the older np.array(..., copy=False)) contract triggers this.","commonSituations":"Downstream libraries (e.g. dask, xarray, numba interop) that pass copy=False for memory efficiency, or hand-written np.asarray(..., copy=False) calls. Also surfaces with numpy>=2.0 where __array__ gained the copy kwarg.","solutions":["Allow the copy: drop copy=False, or pass copy=True when you need object dtype.","Use arr.to_numpy(dtype=object) (lets pandas choose copy semantics) or arr.astype(object).","If you truly need zero-copy, keep the native int64/datetime64 dtype instead of converting to object."],"exampleFix":"// before\nimport numpy as np\narr = pd.date_range('2020', periods=3)._data\nnp.asarray(arr, dtype=object, copy=False)  # ValueError\n\n// after\nnp.asarray(arr, dtype=object)  # copy permitted","handlingStrategy":"validation","validationCode":"import numpy as np\ndef to_object_array(arr):\n    try:\n        return np.asarray(arr, dtype=object, copy=False)\n    except ValueError:\n        return np.asarray(arr, dtype=object)","typeGuard":"from typing import Any\n\ndef allows_nocopy_object(arr: Any) -> bool:\n    # object-dtype materialisation always copies; never zero-copy\n    return False","tryCatchPattern":"try:\n    np.asarray(arr, dtype=object, copy=False)\nexcept ValueError as e:\n    if 'Unable to avoid copy' in str(e):\n        np.asarray(arr, dtype=object)\n    else:\n        raise","preventionTips":["Never pass copy=False with dtype=object on datetime-like arrays.","Prefer arr.to_numpy(dtype=object) over np.asarray."],"tags":["datetime","numpy","copy"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}