{"record":{"id":"82ff92e4acd21bb8","repo":"pandas-dev/pandas","slug":"cannot-modify-read-only-array-82ff92","errorCode":null,"errorMessage":"Cannot modify read-only array","messagePattern":"Cannot modify read-only array","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/base.py","lineNumber":569,"sourceCode":"        # *do* choose to implement __setitem__, then some semantics should be\n        # observed:\n        #\n        # * Setting multiple values : ExtensionArrays should support setting\n        #   multiple values at once, 'key' will be a sequence of integers and\n        #  'value' will be a same-length sequence.\n        #\n        # * Broadcasting : For a sequence 'key' and a scalar 'value',\n        #   each position in 'key' should be set to 'value'.\n        #\n        # * Coercion : Most users will expect basic coercion to work. For\n        #   example, a string like '2018-01-01' is coerced to a datetime\n        #   when setting on a datetime64ns array. In general, if the\n        #   __init__ method coerces that value, then so should __setitem__\n        # Note, also, that Series/DataFrame.where internally use __setitem__\n        # on a copy of the data.\n        # Check if the array is readonly\n        if self._readonly:\n            raise ValueError(\"Cannot modify read-only array\")\n\n        raise NotImplementedError(f\"{type(self)} does not implement __setitem__.\")\n\n    def __len__(self) -> int:\n        \"\"\"\n        Length of this array\n\n        Returns\n        -------\n        length : int\n        \"\"\"\n        raise AbstractMethodError(self)\n\n    def __iter__(self) -> Iterator[Any]:\n        \"\"\"\n        Iterate over elements of the array.\n        \"\"\"\n        # This needs to be implemented so that pandas recognizes extension","sourceCodeStart":551,"sourceCodeEnd":587,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/base.py#L551-L587","documentation":"Raised by ExtensionArray.__setitem__ when `self._readonly` is True. Several immutable extension arrays (and views flagged readonly after slicing/astype-is-view operations) set _readonly to prevent in-place mutation; any assignment via `arr[i] = value` (including internal use by Series.where on a copy) then raises ValueError. The check runs before any subclass-specific __setitem__ logic.","triggerScenarios":"Calling `arr[i] = v` or `s.iloc[i] = v` on an immutable extension array (e.g. some ArrowExtensionArray views, categorical copies marked readonly, or arrays explicitly flagged readonly). Triggered internally when pandas tries to use __setitem__ on a readonly view produced by astype/slicing.","commonSituations":"Mutating a Series that was created from a readonly view; chaining astype followed by in-place assignment; libraries handing pandas readonly buffers; categorical/date arrays marked immutable.","solutions":["Force a writable copy before assigning: `s = s.copy(); s.iloc[i] = v`.","Avoid in-place mutation of slices/views; rebuild with pd.concat/where instead.","Check `s.array._readonly` (or equivalent) before attempting mutation.","Use functional updates: `s = s.mask(cond, new_value)` rather than item assignment."],"exampleFix":"# before\ns = pd.Series([1,2,3], dtype=\"Int64\")\nview = s.astype(\"Int64\")  # may be readonly view\nview.iloc[0] = 99  # ValueError: Cannot modify read-only array\n\n# after\nview = s.astype(\"Int64\").copy()\nview.iloc[0] = 99","handlingStrategy":"validation","validationCode":"def safe_setitem(arr, key, value):\n    if getattr(arr, \"_readonly\", False):\n        arr = arr.copy()\n    arr[key] = value\n    return arr","typeGuard":"def is_readonly(arr) -> bool:\n    return bool(getattr(arr, \"_readonly\", False))","tryCatchPattern":"try:\n    arr[key] = value\nexcept ValueError as e:\n    if \"read-only\" in str(e):\n        arr = arr.copy()\n        arr[key] = value\n    else:\n        raise","preventionTips":["Call .copy() before mutating views produced by astype/slicing.","Prefer functional updates (mask/where/replace) over item assignment.","Check array._readonly in helper functions that accept arbitrary extension arrays."],"tags":["extension-array","readonly","mutation","immutability"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}