diff --git a/pandas/core/series.py b/pandas/core/series.py index 5ed094349caaa..91926a53a8559 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -928,7 +928,7 @@ def _slice(self, slobj: slice, axis: AxisInt = 0) -> Series: # axis kwarg is retained for compat with NDFrame method # _slice is *always* positional mgr = self._mgr.get_slice(slobj, axis=axis) - out = self._constructor_from_mgr(mgr, axes=mgr.axes) + out = self._constructor_from_mgr(mgr, axes=mgr.axes).copy(deep=True) out._name = self._name return out.__finalize__(self) diff --git a/pandas/tests/series/methods/test_slice.py b/pandas/tests/series/methods/test_slice.py new file mode 100644 index 0000000000000..459696f8f20b7 --- /dev/null +++ b/pandas/tests/series/methods/test_slice.py @@ -0,0 +1,27 @@ +import gc + +from pandas import Series + + +class Dummy: + def __init__(self, val): + self.val = val + + +def count_dummy_instances(): + gc.collect() + return sum(1 for obj in gc.get_objects() if isinstance(obj, Dummy)) + + +def test_slicing_releases_dummy_instances(): + """Ensure Series slicing does not retain references to original Dummy data.""" + NDATA = 100_000 + baseline = count_dummy_instances() + a = Series([Dummy(i) for i in range(NDATA)]) + a = a[-1:] + gc.collect() + after = count_dummy_instances() + retained = after - baseline + assert retained <= 1, ( + f"{retained} Dummy instances were retained; expected at most 1" + )