diff --git a/pandas/core/series.py b/pandas/core/series.py index ff03b5071e3b1..b1ac6225cb71e 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1175,7 +1175,7 @@ def _get_values_tuple(self, key: tuple): # If key is contained, would have returned by now indexer, new_index = self.index.get_loc_level(key) new_ser = self._constructor(self._values[indexer], index=new_index, copy=False) - if using_copy_on_write() and isinstance(indexer, slice): + if isinstance(indexer, slice): new_ser._mgr.add_references(self._mgr) # type: ignore[arg-type] return new_ser.__finalize__(self) @@ -1217,7 +1217,7 @@ def _get_value(self, label, takeable: bool = False): new_ser = self._constructor( new_values, index=new_index, name=self.name, copy=False ) - if using_copy_on_write() and isinstance(loc, slice): + if isinstance(loc, slice): new_ser._mgr.add_references(self._mgr) # type: ignore[arg-type] return new_ser.__finalize__(self) diff --git a/pandas/tests/copy_view/test_indexing.py b/pandas/tests/copy_view/test_indexing.py index 355eb2db0ef09..205e80088d8f4 100644 --- a/pandas/tests/copy_view/test_indexing.py +++ b/pandas/tests/copy_view/test_indexing.py @@ -1141,16 +1141,18 @@ def test_set_value_copy_only_necessary_column( assert np.shares_memory(get_array(df, "a"), get_array(view, "a")) -def test_series_midx_slice(using_copy_on_write): +def test_series_midx_slice(using_copy_on_write, warn_copy_on_write): ser = Series([1, 2, 3], index=pd.MultiIndex.from_arrays([[1, 1, 2], [3, 4, 5]])) + ser_orig = ser.copy() result = ser[1] assert np.shares_memory(get_array(ser), get_array(result)) - # TODO(CoW-warn) should warn -> reference is only tracked in CoW mode, so - # warning is not triggered - result.iloc[0] = 100 + with tm.assert_cow_warning(warn_copy_on_write): + result.iloc[0] = 100 if using_copy_on_write: + tm.assert_series_equal(ser, ser_orig) + else: expected = Series( - [1, 2, 3], index=pd.MultiIndex.from_arrays([[1, 1, 2], [3, 4, 5]]) + [100, 2, 3], index=pd.MultiIndex.from_arrays([[1, 1, 2], [3, 4, 5]]) ) tm.assert_series_equal(ser, expected) @@ -1181,16 +1183,15 @@ def test_getitem_midx_slice( assert df.iloc[0, 0] == 100 -def test_series_midx_tuples_slice(using_copy_on_write): +def test_series_midx_tuples_slice(using_copy_on_write, warn_copy_on_write): ser = Series( [1, 2, 3], index=pd.MultiIndex.from_tuples([((1, 2), 3), ((1, 2), 4), ((2, 3), 4)]), ) result = ser[(1, 2)] assert np.shares_memory(get_array(ser), get_array(result)) - # TODO(CoW-warn) should warn -> reference is only tracked in CoW mode, so - # warning is not triggered - result.iloc[0] = 100 + with tm.assert_cow_warning(warn_copy_on_write): + result.iloc[0] = 100 if using_copy_on_write: expected = Series( [1, 2, 3],