From 5bac3d0950679674edd84757654f04c76c7a521e Mon Sep 17 00:00:00 2001 From: Matthew Roeschke <10647082+mroeschke@users.noreply.github.com> Date: Tue, 26 Mar 2024 14:21:03 -0700 Subject: [PATCH] Make series.array read-only --- pandas/core/internals/blocks.py | 6 +++--- pandas/tests/copy_view/test_array.py | 7 +++++++ 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index a7cdc7c39754d..8725d35d91dc1 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -2112,7 +2112,9 @@ def is_view(self) -> bool: @property def array_values(self) -> ExtensionArray: - return NumpyExtensionArray(self.values) + values = self.values.view() + values.flags.writeable = False + return NumpyExtensionArray(values) def get_values(self, dtype: DtypeObj | None = None) -> np.ndarray: if dtype == _dtype_obj: @@ -2364,6 +2366,4 @@ def external_values(values: ArrayLike) -> ArrayLike: values = values.view() values.flags.writeable = False - # TODO(CoW) we should also mark our ExtensionArrays as read-only - return values diff --git a/pandas/tests/copy_view/test_array.py b/pandas/tests/copy_view/test_array.py index bb238d08bd9bd..29ef695e9cff8 100644 --- a/pandas/tests/copy_view/test_array.py +++ b/pandas/tests/copy_view/test_array.py @@ -141,3 +141,10 @@ def test_empty_dataframe(): df = DataFrame() arr = np.asarray(df) assert arr.flags.writeable is True + + +def test_series_array_not_writable(): + # GH 58007 + ser = Series([1, 2]) + with pytest.raises(ValueError, match="assignment destination is read-only"): + ser.array[0] = 2