diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index b3f5fb6f0291a..d180945d85d00 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -9,6 +9,7 @@ FrozenSet, Hashable, List, + NewType, Optional, Sequence, Tuple, @@ -139,7 +140,9 @@ def index_arithmetic_method(self, other): _o_dtype = np.dtype(object) -_Identity = object + + +_Identity = NewType("_Identity", object) def _new_Index(cls, d): @@ -238,7 +241,7 @@ def _outer_indexer(self, left, right): _typ = "index" _data: Union[ExtensionArray, np.ndarray] - _id = None + _id: _Identity _name: Label = None # MultiIndex.levels previously allowed setting the index name. We # don't allow this anymore, and raise if it happens rather than @@ -453,8 +456,9 @@ def _simple_new(cls, values, name: Label = None): result._index_data = values result._name = name result._cache = {} + result._reset_identity() - return result._reset_identity() + return result @cache_readonly def _constructor(self): @@ -558,15 +562,16 @@ def is_(self, other) -> bool: -------- Index.identical : Works like ``Index.is_`` but also checks metadata. """ - # use something other than None to be clearer - return self._id is getattr(other, "_id", Ellipsis) and self._id is not None + try: + return self._id is other._id + except AttributeError: + return False - def _reset_identity(self): + def _reset_identity(self) -> None: """ Initializes or resets ``_id`` attribute with new object. """ - self._id = _Identity() - return self + self._id = _Identity(object()) def _cleanup(self): self._engine.clear_mapping() diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 2ce4538a63d25..38a0d18ac732d 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -316,7 +316,9 @@ def __new__( new_codes = result._verify_integrity() result._codes = new_codes - return result._reset_identity() + result._reset_identity() + + return result def _validate_codes(self, level: List, code: List): """ diff --git a/pandas/tests/arithmetic/test_object.py b/pandas/tests/arithmetic/test_object.py index 02cb4f4d7a606..e0c03f28f7af5 100644 --- a/pandas/tests/arithmetic/test_object.py +++ b/pandas/tests/arithmetic/test_object.py @@ -343,8 +343,9 @@ def _simple_new(cls, values, name=None, dtype=None): result._index_data = values result._name = name result._calls = 0 + result._reset_identity() - return result._reset_identity() + return result def __add__(self, other): self._calls += 1