Skip to content

Commit

Permalink
PERF: break reference cycle in Index._engine
Browse files Browse the repository at this point in the history
  • Loading branch information
crepererum committed Jul 29, 2019
1 parent 3b96ada commit 64d2f7e
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 1 deletion.
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.25.1.rst
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ Interval
Indexing
^^^^^^^^

- Break reference cycle in :meth:`Index._engine` (:issue:`27585`)
-
-
-
Expand Down
6 changes: 5 additions & 1 deletion pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -687,7 +687,11 @@ def _cleanup(self):
@cache_readonly
def _engine(self):
# property, for now, slow to look up
return self._engine_type(lambda: self._ndarray_values, len(self))

# to avoid a refernce cycle, bind `_ndarray_values` to a local variable, so
# `self` is not passed into the lambda.
_ndarray_values = self._ndarray_values
return self._engine_type(lambda: _ndarray_values, len(self))

# --------------------------------------------------------------------
# Array-Like Methods
Expand Down
8 changes: 8 additions & 0 deletions pandas/tests/indexes/test_base.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from collections import defaultdict
from datetime import datetime, timedelta
import gc
from io import StringIO
import math
import operator
Expand Down Expand Up @@ -2424,6 +2425,13 @@ def test_deprecated_contains(self):
with tm.assert_produces_warning(FutureWarning):
index.contains(1)

def test_engine_reference_cycle(self):
# https://github.com/pandas-dev/pandas/issues/27585
index = pd.Index([1, 2, 3])
nrefs_pre = len(gc.get_referrers(index))
index._engine
assert len(gc.get_referrers(index)) == nrefs_pre


class TestMixedIntIndex(Base):
# Mostly the tests from common.py for which the results differ
Expand Down

0 comments on commit 64d2f7e

Please sign in to comment.