Skip to content

Commit 5210c8b

Browse files
setitem exceptions for complex raise ValueError
In certain cases where Python throws a TypeError for complex values where it would throw ValueError for real values, transform exception to ValueError. Signed-off-by: Michael Tiemann <72577720+MichaelTiemannOSC@users.noreply.github.com>
1 parent 29aa747 commit 5210c8b

File tree

2 files changed

+9
-3
lines changed

2 files changed

+9
-3
lines changed

pandas/core/arrays/_mixins.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -259,7 +259,13 @@ def shift(self, periods: int = 1, fill_value=None):
259259
def __setitem__(self, key, value) -> None:
260260
key = check_array_indexer(self, key)
261261
value = self._validate_setitem_value(value)
262-
self._ndarray[key] = value
262+
try:
263+
self._ndarray[key] = value
264+
except TypeError as exc:
265+
# Don't let Python's handling of `complex` make extra complexity for Pandas
266+
if self._ndarray.dtype.kind == "c":
267+
raise ValueError(*(x.replace("real", "complex") for x in exc.args))
268+
raise exc
263269

264270
def _validate_setitem_value(self, value):
265271
return value

pandas/tests/extension/base/setitem.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -343,8 +343,8 @@ def test_setitem_slice_array(self, data):
343343

344344
def test_setitem_scalar_key_sequence_raise(self, data):
345345
arr = data[:5].copy()
346-
# complex128 data raises TypeError; other numeric types raise ValueError
347-
with pytest.raises((ValueError, TypeError)):
346+
msg = "" # messages vary by subclass, so we do not test it
347+
with pytest.raises(ValueError, match=msg):
348348
arr[0] = arr[[0, 1]]
349349

350350
def test_setitem_preserves_views(self, data):

0 commit comments

Comments
 (0)