diff --git a/bigframes/core/indexes/base.py b/bigframes/core/indexes/base.py index bc8b47d216..f653b8700b 100644 --- a/bigframes/core/indexes/base.py +++ b/bigframes/core/indexes/base.py @@ -174,6 +174,11 @@ def dtypes(self) -> pandas.Series: index=typing.cast(typing.Tuple, self._block.index.names), ) + def __setitem__(self, key, value) -> None: + """Index objects are immutable. Use Index constructor to create + modified Index.""" + raise TypeError("Index does not support mutable operations") + @property def size(self) -> int: return self.shape[0] diff --git a/tests/system/small/test_index.py b/tests/system/small/test_index.py index 3b9854be26..c7e316a9d2 100644 --- a/tests/system/small/test_index.py +++ b/tests/system/small/test_index.py @@ -499,3 +499,29 @@ def test_index_item_with_empty(session): with pytest.raises(ValueError, match=re.escape(expected_message)): bf_idx_empty.item() + + +@pytest.mark.parametrize( + ("key", "value"), + [ + (0, "string_value"), + (1, 42), + ("label", None), + (-1, 3.14), + ], +) +def test_index_setitem_different_types(scalars_dfs, key, value): + """Tests that custom Index setitem raises TypeError.""" + scalars_df, _ = scalars_dfs + index = scalars_df.index + + with pytest.raises(TypeError, match="Index does not support mutable operations"): + index[key] = value + + +def test_custom_index_setitem_error(): + """Tests that custom Index setitem raises TypeError.""" + custom_index = bpd.Index([1, 2, 3, 4, 5], name="custom") + + with pytest.raises(TypeError, match="Index does not support mutable operations"): + custom_index[2] = 999