Skip to content

BUG: Fix memory leak when slicing Series and assigning to self #61426

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
27 changes: 27 additions & 0 deletions pandas/tests/series/methods/test_slice.py
Original file line number Diff line number Diff line change
@@ -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"
)
Loading