{"record":{"id":"5d02ab71742ccb47","repo":"pandas-dev/pandas","slug":"cannot-modify-read-only-array-5d02ab","errorCode":null,"errorMessage":"Cannot modify read-only array","messagePattern":"Cannot modify read-only array","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/string_.py","lineNumber":871,"sourceCode":"            value = extract_array(value, extract_numpy=True)\n            if not is_array_like_deprecate_non_pandas(value):\n                value = np.asarray(value, dtype=object)\n            elif isinstance(value.dtype, type(self.dtype)):\n                return value\n            else:\n                # cast categories and friends to arrays to see if values are\n                # compatible, compatibility with arrow backed strings\n                value = np.asarray(value)\n            if len(value) and not lib.is_string_array(value, skipna=True):\n                raise TypeError(\n                    \"Invalid value for dtype 'str'. Value should be a \"\n                    \"string or missing value (or array of those).\"\n                )\n        return value\n\n    def __setitem__(self, key, value) -> None:\n        if self._readonly:\n            raise ValueError(\"Cannot modify read-only array\")\n\n        value = self._validate_setitem_value(value)\n\n        key = check_array_indexer(self, key)\n        scalar_key = lib.is_scalar(key)\n        scalar_value = lib.is_scalar(value)\n        if scalar_key and not scalar_value:\n            raise ValueError(\"setting an array element with a sequence.\")\n\n        if not scalar_value:\n            if value.dtype == self.dtype:\n                value = value._ndarray\n            else:\n                value = np.asarray(value)\n                mask = isna(value)\n                if mask.any():\n                    value = value.copy()\n                    value[isna(value)] = self.dtype.na_value","sourceCodeStart":853,"sourceCodeEnd":889,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/string_.py#L853-L889","documentation":"StringArray.__setitem__ checks the _readonly flag at the top and raises ValueError if the array is read-only. Read-only state is set when the underlying ndarray has writeable=False (e.g., from np.frombuffer, memory mapping, or explicit flags.writeable=False) or when the array is a view into protected memory.","triggerScenarios":"Calling string_array[i] = 'x' on an array whose _readonly is True, e.g., one created from a memory-mapped buffer, a zero-copy slice of a read-only buffer, or after arr.flags.writeable = False on the backing ndarray.","commonSituations":"Loading data via mmap or shared memory; operating on arrays returned by libraries that mark buffers read-only; defensive copies omitted in a pipeline.","solutions":["Copy the array before mutating: arr = arr.copy().","Avoid setting arr.flags.writeable = False on arrays you intend to modify.","Detect read-only state up front and branch to a copy path."],"exampleFix":"// before\nreadonly_arr[0] = 'x'\n\n// after\narr = readonly_arr.copy()\narr[0] = 'x'","handlingStrategy":"validation","validationCode":"if getattr(string_array, '_readonly', False):\n    string_array = string_array.copy()\nstring_array[i] = 'x'","typeGuard":"def is_writable(arr) -> bool:\n    return not getattr(arr, '_readonly', False)","tryCatchPattern":null,"preventionTips":["Copy arrays before mutating when they may originate from read-only memory.","Do not set arr.flags.writeable = False on arrays you later modify.","Check the _readonly flag at the start of mutation paths."],"tags":["string-array","readonly","setitem","memory"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}