Skip to content

Commit f391180

Browse files
y-pwesm
y-p
authored andcommitted
ENH: Eliminate __setitem__ in pd.Index
`Index` inherits from np.ndarray, yet implements an immutable datatype, Pythonic duck-typing would suggest that the presence of __setitem__ signals a mutable datatype, while the overriden implementaion just raises an exception - a bait and switch. Python does not offer a really clean way to eliminate an attribute inherited from a superclass, but overriding __getattribute__ gives us the same end result. squash with 218fe0a
1 parent 85d982d commit f391180

File tree

3 files changed

+7
-6
lines changed

3 files changed

+7
-6
lines changed

pandas/core/index.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -305,9 +305,11 @@ def __contains__(self, key):
305305
def __hash__(self):
306306
return hash(self.view(np.ndarray))
307307

308-
def __setitem__(self, key, value):
309-
"""Disable the setting of values."""
310-
raise Exception(str(self.__class__) + ' object is immutable')
308+
def __getattribute__(self,name):
309+
if name=="__setitem__": # emulate an Immutable ndarray
310+
raise AttributeError(str(self.__class__) + ' object is immutable')
311+
else:
312+
return object.__getattribute__(self,name)
311313

312314
def __getitem__(self, key):
313315
"""Override numpy.ndarray's __getitem__ method to work as desired"""

pandas/tests/test_format.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -765,7 +765,7 @@ def test_to_html_with_classes(self):
765765
<table border="1" class="dataframe sortable draggable">
766766
<tbody>
767767
<tr>
768-
<td>Index([], dtype=object)</td>
768+
<td>Index((), dtype=object)</td>
769769
<td>Empty DataFrame</td>
770770
</tr>
771771
</tbody>

pandas/tests/test_index.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,7 @@ def test_sort(self):
5757
self.assertRaises(Exception, self.strIndex.sort)
5858

5959
def test_mutability(self):
60-
self.assertRaises(Exception, self.strIndex.__setitem__, 5, 0)
61-
self.assertRaises(Exception, self.strIndex.__setitem__, slice(1,5), 0)
60+
self.assertFalse(hasattr(self.strIndex,"__setitem__"))
6261

6362
def test_constructor(self):
6463
# regular instance creation

0 commit comments

Comments
 (0)